Video in progress
What is the Null Object pattern? Compare it with `Optional`.
Null Object means returning a real implementation that "does nothing" instead of null, so the caller can keep calling methods without a check. Optional openly shows in the type itself that a value may be absent, and forces the caller to deal with that case.
📖 Answer
A Null Object example, a discount:
interface Discount {
BigDecimal apply(BigDecimal price);
Discount NONE = price -> price; // null object
}
Discount d = promoRepo.findActive(code).orElse(Discount.NONE);
BigDecimal total = d.apply(price); // no need for if (d != null)
NOPLogger in loggers and Collections.emptyList() are the same idea: an empty list is much more convenient than null, because for-each works directly.
When Null Object, when Optional:
- "Nothing" is also a correct, normal state, and there's a neutral behavior that fits it (no discount = the price stays the same): Null Object.
- The absence matters to the business and the caller has to react differently each time (user not found → 404):
Optional.
The risk of Null Object is that it can hide a bug. If a configuration mistake wires in a NoOpSmsSender instead of the real SmsSender, there's no exception at all: the SMS just doesn't go out. So such implementations should at least write a debug log.
Don't use Optional as a field or a method parameter: it was designed for return values.
Sign up to mark studied questions and save your progress.