Every way to handle a missing value
null and NullPointerException, guard clauses, getOrDefault, case null, Optional, and when to throw instead.
First decide what "missing" means here.
- It must never be missing (a required argument) → check it at the boundary with a guard clause or
Objects.requireNonNull, and fail fast with a clear message. - Missing has a sensible default (no count yet means 0) →
map.getOrDefault(key, 0), oroptional.orElse(...). - A lookup can legitimately find nothing → return
Optional<T>so every caller must decide what to do; don't returnnull. - Missing is a real error the caller should handle → throw an exception that says what was missing.
- A switch over an object that might be null →
case nullhandles it explicitly instead of throwing.
Where null comes from
Term
null
A reference to no object at all.
Example
String s = null; s.length();What calling a method through null throws.
Section
null and NullPointerException
Why it happens and how to read the helpful message.
Keeping null out
Check the bad case at the top of a method and leave early.
Section
Validation and invariants
Reject bad arguments in the constructor so an object is never half-valid.
Section
case null in a switch
Handle null as its own case instead of crashing.
Saying "maybe absent" in the type
Section
Maps and getOrDefault
get returns null for a missing key; getOrDefault doesn't.
Term
Optional
Example
findEmail(user).orElse("(none)")A box that holds a value or is empty, so callers must decide.
Section
Optional
of, ofNullable, orElse, orElseGet, map and orElseThrow.