Video in progress
What options are there instead of returning `null` when a method finds nothing?
Optional for a single value, an empty collection for a collection, a Null Object when you need "do-nothing" behavior, and a clear exception when it is a real error. Each has its place.
📖 Answer
The problem with returning null is that it isn't visible in the type. From the signature User findUser(id) you can't tell that null may come back, and the NPE is thrown later, somewhere else.
Optionalfor "may or may not be there":
Optional<User> findByEmail(String email);
userRepo.findByEmail(email)
.map(User::displayName)
.orElse("Mehmon");
Don't use it as a field, a method parameter or a collection element; it was designed only for return types.
- An empty collection:
return orders.isEmpty() ? List.of() : orders; // never null
The caller can write a for loop directly.
- A Null Object, an "empty" implementation with behavior:
interface DiscountPolicy { Money apply(Money price); }
enum NoDiscount implements DiscountPolicy {
INSTANCE;
public Money apply(Money price) { return price; }
}
The if (policy != null) checks disappear from the code.
- An exception, if absence is an error: when a
/orders/{id}request finds no order, throwOrderNotFoundExceptionand return a 404. Rather than returning anOptionaland making every caller writeorElseThrow, it is more convenient to offer bothgetByIdandfindById.
Sign up to mark studied questions and save your progress.