Video in progress
Where should you not use Optional?
Optional is meant mainly for a value returned from a method. Using it as an entity or DTO field, as a method parameter, or as a collection element, and returning Optional<List> instead of a collection, are widespread mistakes.
📖 Answer
Brian Goetz, who added Optional to Java, also described it as "a limited mechanism for return values". In practice, avoid the following.
As a field:
class User {
private Optional<String> phone; // bad
}
Optional is not Serializable, causes problems with JPA and Jackson, and adds another object on top of every object. Make the field a plain String phone and let the getter return Optional<String> phone(): that's enough.
As a parameter:
void notify(User u, Optional<String> template); // bad
The caller can pass Optional.empty() or even null, so now there are three states. An overload or two separate methods is clearer.
With collections:
Optional<List<Order>>: no, return an empty list;List<Optional<Order>>: usually a sign you need to clean it up withflatMap(Optional::stream).
And the funniest one: returning null from a method that returns Optional. In that case all of the caller's defenses are useless.
On a hot path (millions of calls per second) the extra object creation can be noticeable, but don't treat it as a problem until a profile shows it.
Sign up to mark studied questions and save your progress.