How to Eliminate Redundant Null Checks in Java with the Null Object Pattern
This article explains why excessive null‑checking code appears in Java projects, distinguishes valid versus error null values, and offers practical techniques—including asserts, exceptions, empty collections, and the Null Object pattern—to write cleaner, safer backend code.
To avoid null pointer exceptions, developers often write repetitive null‑checking code, which can become ugly and unnecessary.
Key insight: Distinguish whether
nullis a valid response or an error condition.
When
nullindicates an invalid argument, the method should fail fast by throwing an exception or using an
assertwith a clear message.
When
nullis a legitimate “empty” value (e.g., a missing database record), prefer returning an empty collection or a dedicated empty object instead of
null.
Practical recommendations:
Return an empty
List(or other collection) rather than
null.
If the return type is not a collection, return a well‑defined empty object.
Applying the Null Object pattern:
<code>public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
public class MyParser implements Parser {
private static final Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// …
if (/* cannot find any actions */) {
return DO_NOTHING;
}
// …
}
}
</code>Usage comparison:
<code>// Redundant null checks
Parser parser = ParserFactory.getParser();
if (parser == null) { /* handle */ }
Action action = parser.findAction(input);
if (action == null) { /* do nothing */ } else { action.doSomething(); }
// Concise version
ParserFactory.getParser().findAction(input).doSomething();
</code>Additional tips:
Prefer
"constant".equals(variable)to avoid NPE.
Java 8’s
Optionalcan encapsulate potentially null values, though it adds verbosity.
If a method must return
null, consider throwing an exception instead.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.