Card 06/ 08
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.
| Position | Use it? | Why |
|---|---|---|
| A method's return type | Yes, this is the job | The caller cannot miss that absence is possible |
| A field | No | It adds an object per field, and it is not serialisable (it cannot be written out as bytes by Java's built-in serialisation) |
| A parameter | No | The caller now has to wrap, and a null Optional is possible |
| A collection's element type | No | An 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.
← → move through sections and cards