ConceptDifficulty: Advanced1 min

Where Optional Does Not Belong: Fields, Parameters and Collections

Designed as a return type, and a source of new problems in every other position.

Optional is a container that holds either one value or nothing, and it was designed for one position, a method's return type. As a field, a parameter or a collection's element type it adds cost and extra cases instead of removing them.

Where Optional belongs and where it does not
PositionUse it?Why
A method's return typeYes, this is the jobThe caller cannot miss that absence is possible
A fieldNoIt adds an object per field, and it is not serialisable (it cannot be written out as bytes by Java's built-in serialisation)
A parameterNoThe caller now has to wrap, and a null Optional is possible
A collection's element typeNoAn empty collection already says nothing is there

The parameter row is the one that looks most reasonable and works worst. A method taking Optional<String> can be handed null, an empty Optional or a present one: three cases instead of two, and the caller has to build a wrapper to make an ordinary call.

Two overloads are almost always better: one taking the value and one not. The caller then says which situation they are in by which method they call.

So the rule is narrow on purpose: a return type where absence is a normal outcome, and nothing else. Used there it removes null checks; used elsewhere it adds a wrapper.