The null check that arrives too late
A medium Java puzzle in the null handling family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
The null check comes after the dereference. A null name throws a plain NullPointerException from trim before the helpful message can ever be produced, so the check is dead code.
The fix
How to avoid it next time
Validate arguments first, ideally in the same expression as the assignment.
Want the background? Read Defensive checks: assert and preconditions in the Java concepts library.
About null handling
NullPointerException is still the most common production exception. Chained calls, auto-unboxing, maps that return null for missing keys and Optional used the wrong way all hide a null until the worst moment.
In code review: Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.
More puzzles in this family
Frequently asked questions
What is the bug in "The null check that arrives too late"?
The null check comes after the dereference. A null name throws a plain NullPointerException from trim before the helpful message can ever be produced, so the check is dead code. The faulty line is line 7: this.name = name.trim();
How do I fix it?
Replace it with: this.name = Objects.requireNonNull(name, "name must not be null").trim();. Validate arguments first, ideally in the same expression as the assignment.
How do I catch null handling in code review?
Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.