Video in progress
What is wrong with this value object, and how does it show up in a `Set` or a cache?
public record Money(BigDecimal amount, Currency currency) { }
var a = new Money(new BigDecimal("10.0"), UZS);
var b = new Money(new BigDecimal("10.00"), UZS);
System.out.println(a.equals(b));
A record's equals calls BigDecimal.equals, which also compares the scale: 10.0 and 10.00 are not equal. As a result, the same amount becomes two different keys. You need to normalize the scale in the compact constructor.
📖 Answer
It prints false. The whole point of a value object is that if the values are equal, the objects are equal. Here, BigDecimal("10.0") and BigDecimal("10.00") have different scales, and BigDecimal.equals doesn't consider them equal. compareTo returns 0, which is why this bug often stays invisible in tests.
Where it shows up: in a Set<Money> the same amount appears twice, a key isn't found in a Map or cache, and assertEquals fails against a value read from the database (if the column is numeric(19,2), it returns 10.00).
The fix is to establish the invariant at creation time:
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(amount);
Objects.requireNonNull(currency);
amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.UNNECESSARY);
}
public Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("valyuta boshqa");
return new Money(amount.add(other.amount), currency);
}
}
RoundingMode.UNNECESSARY is deliberate: if a value like 10.005 comes in, it throws an ArithmeticException instead of rounding silently. If you need rounding, you agree on it with the business and write an explicit mode.
The rest of the value object rules come for free with a record: immutable, no identity. The types inside just have to be immutable too, with a correct equals, and BigDecimal is the trap here.
Sign up to mark studied questions and save your progress.