Card 06/ 08
All 8 cards
ConceptDifficulty: Advanced1 min
Where Optional Does Not Belong
Optional removes a whole class of bug in one position and adds problems in the others. It was designed as a return type, and the places it is not designed for are worth naming.
| 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 |
| 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.