Card 08/ 08
Recap: Optional
What the type says, how to unwrap it, the two traps, and where it belongs, with where each was.
Optional comes down to the five ideas below, each listed with the card that covers it.
| The idea | Where |
|---|---|
Optional puts "there might be nothing" into the signature | Optional: A Return Type That Says There Might Be Nothing |
orElse for a value in hand, orElseGet for anything that costs | orElse vs orElseGet vs orElseThrow |
The argument to orElse is computed whether or not it is needed | orElse Runs Its Fallback Even When the Value Is Present |
get() without a check throws, exactly as the null would have | Optional.get() Without a Check Brings the Null Bug Back |
| A return type, never a field, a parameter or an element | Where Optional Does Not Belong: Fields, Parameters and Collections |
Optional makes absence visible and does not make anybody handle it. Everything that goes wrong with it is a caller unwrapping it immediately, which puts the original problem back under a longer name.
← → move through sections and cards