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.

  1. Optional for "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.

  1. An empty collection:
return orders.isEmpty() ? List.of() : orders; // never null

The caller can write a for loop directly.

  1. 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.

  1. An exception, if absence is an error: when a /orders/{id} request finds no order, throw OrderNotFoundException and return a 404. Rather than returning an Optional and making every caller write orElseThrow, it is more convenient to offer both getById and findById.