How do you handle the following scenario without null?
You have this problem (In Java):
BigDecimal sales = ...; BigDecimal cost = ...; BigDecimal profit = sales.subtract(cost); // Profit Margin = profit / sales BigDecimal profitMargin = profit.divide(sales, 20, RoundingMode.HALF_UP);
sales is sometimes zero, we turn the last line into:
BigDecimal profitMargin = sales.compareTo(BigDecimal.ZERO) == 0 ? null : profit.divide(sales, 20, RoundingMode.HALF_UP);
In which case if
profitMargin == null, then we know what that means. If you make
profitMargin = 0, that isn't really correct, nor is
infinity a good value either. It seems best that it would remain undefined. Yet, it is an "unexploded bomb." So, what's the best way to handle this?
This questions as originally asked on Stack Overflow, and also referred me to the question Are null references really a bad thing?