Optional: Killing the Null Check

Optional: Killing the Null Check in Java: is the most common exception in Java, and the reason is structural: a method returning gives no hint about whether it…

Concept Explanation

NullPointerException is the most common exception in Java, and the reason is structural: a method returning User gives no hint about whether it might return nothing.

Optional<User> makes absence part of the type. The compiler now forces you to consider the empty case.


Creating One

Optional<String> present = Optional.of("value");        // throws if null
Optional<String> maybe   = Optional.ofNullable(getName()); // null → empty
Optional<String> empty   = Optional.empty();

Consuming One

Optional<User> found = repo.findByEmail(email);

// Default value
User user = found.orElse(User.guest());

// Lazily computed default — only runs when empty
User user = found.orElseGet(User::createGuest);

// Throw when absent
User user = found.orElseThrow(() -> new UserNotFoundException(email));

// Act only if present
found.ifPresent(u -> log.info("Found {}", u.getName()));

// Both branches
found.ifPresentOrElse(
    u -> log.info("Found {}", u.getName()),
    () -> log.warn("No user for {}", email));

Chaining

This is the real payoff. Compare the null-check version:

// The pyramid of doom
String city = null;
if (user != null) {
    Address addr = user.getAddress();
    if (addr != null) {
        City c = addr.getCity();
        if (c != null) city = c.getName();
    }
}

with the Optional version:

String city = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .map(City::getName)
    .orElse("Unknown");

Any null along the chain short-circuits to empty. Four levels of nesting become one readable expression.

Use flatMap when the mapper itself returns an Optional:

Optional<String> nickname = findUser(id)
    .flatMap(User::getNickname);        // getNickname() returns Optional<String>

Filter inside the chain:

Optional<User> activeAdult = findUser(id)
    .filter(User::isActive)
    .filter(u -> u.getAge() >= 18);

Where Optional Belongs

UseVerdict
Return type of a lookup✅ exactly what it is for
Local variable in a chain✅ fine
Method parameter❌ overload the method instead
Field on an entity❌ not serialisable; use null
Collection element❌ use an empty collection

For a missing collection, return List.of() — never Optional<List<T>>. An empty list already means "nothing".


Common Mistakes

  1. optional.get() without checking: Reintroduces the exact crash you were avoiding. Use orElseThrow so the intent is explicit.
  2. if (opt.isPresent()) { opt.get() }: Technically safe but no better than a null check. Use map or ifPresent.
  3. orElse with an expensive call: orElse(buildDefault()) evaluates buildDefault() always, even when the value is present. Use orElseGet.
  4. Returning null from a method typed Optional: A special kind of cruelty. Return Optional.empty().
  5. Optional fields in entities: Breaks JPA and Jackson. Keep it at the API boundary.

Best Practices

  • Return Optional from any lookup that can legitimately find nothing.
  • orElseGet for computed defaults, orElse for constants.
  • Never call get() — orElseThrow() says the same thing and reads honestly.
  • Empty collections instead of Optional collections.

Practice Exercises

  1. The Chain: Rewrite a three-level null check as an Optional chain ending in orElse.
  2. The Eager Default: Prove orElse evaluates its argument even when the value is present, by putting a print statement in the default factory. Then fix it with orElseGet.
  3. The Repository: Change a finder returning null to return Optional, and update all callers.