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);
Because 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?
(W1*A1 + W2*A2 + W3*A3) / (W1 + W2 + W3)
, which is valid if at least one ofW1, W2, W3
is nonzero. If an item has zero weight (let's say W1 == 0), the item's value (A1) gives no contribution to the mix (i.e. has no bearing on the result). This is the reason for asking to go back to the business textbook formula and to truly understand what it meant. (Usually, the original formula would handle divisions-by-zero but the "step-by-step calculations" would not.) – rwong Jun 21 '14 at 15:30