The configuration key that was not there
A easy 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
Map.get returns null for a missing key, and calling length on null throws NullPointerException. The code assumes the key is always present, which is true on the developer's machine and false in the container.
The fix
How to avoid it next time
Treat the result of Map.get as nullable. Use getOrDefault, containsKey or Optional.
Want the background? Read Map idioms: merge, compute, entrySet 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 configuration key that was not there"?
Map.get returns null for a missing key, and calling length on null throws NullPointerException. The code assumes the key is always present, which is true on the developer's machine and false in the container. The faulty line is line 7: System.out.println(env.get("TMPDIR").length());
How do I fix it?
Replace it with: System.out.println(env.getOrDefault("TMPDIR", "/tmp").length());. Treat the result of Map.get as nullable. Use getOrDefault, containsKey or Optional.
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.