Card 05/ 08
All 8 cards
GotchaDifficulty: Advanced1 min
Why get() Without a Check Is the null You Replaced
A method returns Optional so that absence cannot be ignored. The caller writes one more character than they would have and ignores it anyway.
String name = findByReference(ref).get().name();Exception in thread "main" java.util.NoSuchElementException: No value presentget() returns the value and throws when there is none. Calling it without checking first is exactly as safe as dereferencing a reference without checking for null — a different exception, in the same place, for the same reason.
| 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.