Video in progress

Middle ☕ Core Java

What are the typical ways to misuse Optional?

Calling get() without a check, making Optional a field or a parameter, returning null instead of an Optional, wrapping a collection in Optional, and doing expensive computation inside orElse.

📖 Answer

  1. get() without a check:
User u = repo.findById(id).get();   // NoSuchElementException

If the value must be there, use orElseThrow(() -> new NotFoundException(...)): the error becomes meaningful.

  1. An Optional that returns null:
Optional<User> find(...) { return null; }  // the whole idea falls apart
  1. A field and a parameter:
class Profile { Optional<String> bio; }       // not serializable, an extra object
void send(Optional<String> cc) { ... }         // awkward for the caller

For a field, use a plain null plus Optional.ofNullable(bio) in the getter; for a parameter, use an overload.

  1. Collections: not Optional<List<Order>>; return an empty list.

  2. orElse and expensive computation:

cache.get(key).orElse(loadFromDb(key));      // the DB is always called!
cache.get(key).orElseGet(() -> loadFromDb(key));
  1. For primitives, use OptionalInt and OptionalLong (no boxing).

  2. Chaining everything:

Optional.ofNullable(x).ifPresent(v -> ...);   // a plain `if (x != null)` is easier to read

Optional was designed for return types, not to eliminate null completely.