Video in progress
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
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.
- An Optional that returns
null:
Optional<User> find(...) { return null; } // the whole idea falls apart
- 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.
-
Collections: not
Optional<List<Order>>; return an empty list. -
orElseand expensive computation:
cache.get(key).orElse(loadFromDb(key)); // the DB is always called!
cache.get(key).orElseGet(() -> loadFromDb(key));
-
For primitives, use
OptionalIntandOptionalLong(no boxing). -
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.
Sign up to mark studied questions and save your progress.