java math library for BigDecimal which allows null values
I guess I don't see the point of the library checking for null. Sure, the library won't throw a NPE, but the caller is eventually going to have to check for it. What is the caller of your above multiply going to do? It can't just use the output. It's going to have to check to see if the returned value is null at some point before it can do anything with the value.
Also, for any application I've ever written, a null is much different than zero. I wouldn't want to use one that treated a null as zero.
If your requirement is that nulls aren't allowed in your DB, I would check for nulls in your DAO layer before writing to the DB.
I had a similar problem (not related to a database though, just needed to sum up a couple of nullable BigDecimal
s). Did not find any library, so had to write the following function myself:
public static BigDecimal add(BigDecimal... addends) {
BigDecimal sum = BigDecimal.ZERO;
if (addends != null) {
for (BigDecimal addend : addends) {
if (addend == null) {
addend = BigDecimal.ZERO;
}
sum = sum.add(addend);
}
}
return sum;
}
The same in Java 8:
public static BigDecimal add(BigDecimal... addends) {
if (addends == null) {
return BigDecimal.ZERO;
}
return Arrays.stream(addends)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
Save the coding, just don't allow null values in the database. Make the default value zero.
As for new BigDecimal(0)
: no, use BigDecimal.ZERO
.