Card 05/ 08
Optional.get() Without a Check Brings the Null Bug Back
Absence made impossible to ignore, and ignored anyway with one method call.
get() returns the value inside an Optional and throws NoSuchElementException when there is none. Calling it without checking first is as unsafe as using a reference without checking for null: a different exception, in the same place, for the same reason.
A method returns Optional so that absence cannot be ignored. The caller writes one more method call than they would have, and ignores it anyway:
String name = findByReference(ref).get().name();Exception in thread "main" java.util.NoSuchElementException: No value presentThe trace is identical in shape to the null version: the failure happens at the call site that assumed a value, and the stack trace does not say why the value was missing.
| Compared on | Returning null | Returning Optional, then get() |
|---|---|---|
| Signature warns the caller | No | Yes |
| Compiler forces a check | No | No |
| Failure when absent | NullPointerException | NoSuchElementException |
Reach for map, orElse, orElseGet, ifPresent or orElseThrow with a message. orElseThrow() is the honest spelling when you genuinely believe it cannot be empty, because the name says what will happen if you are wrong.
← → move through sections and cards