Easy java java-21

How does Optional help avoid null checks?

The 30 second answer

Optional puts "there might be no value" into the method's return type, so the caller can't forget to handle it. Instead of if-not-null checks, I chain map, filter and then orElse, orElseGet or orElseThrow. The Javadoc says it is mainly meant for return values, so I don't use it for fields or parameters, and an Optional variable itself should never be null.

String city = findUser(id)            // Optional<User>
    .map(User::address)
    .map(Address::city)
    .orElse("unknown");

User u = findUser(id).orElseThrow(() -> new NotFoundException(id));

Useful details:

  • orElse(x) always evaluates x; orElseGet(supplier) evaluates it only when empty. Use orElseGet when the default is expensive.
  • Optional.of(null) throws; use Optional.ofNullable for values that may be null.
  • Later additions: ifPresentOrElse, or and stream() (Java 9), orElseThrow() with no arguments (Java 10), isEmpty() (Java 11).
  • Avoid get() without checking; prefer orElseThrow(), which says the same thing more clearly.

The Javadoc API note says Optional is intended primarily as a method return type where there is a clear need to represent "no result". [Opinion] Don't use it for fields, parameters or collections; return an empty collection instead of Optional<List<T>>.

Sources: Optional Javadoc (API note)

Sources (0)
See inline citations in the answer above.