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 null is a valid response or an error condition.
When null indicates an invalid argument, the method should fail fast by throwing an exception or using an assert with a clear message.
When null is 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:
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;
}
// …
}
}Usage comparison:
// 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();Additional tips:
Prefer "constant".equals(variable) to avoid NPE.
Java 8’s Optional can encapsulate potentially null values, though it adds verbosity.
If a method must return null, consider throwing an exception instead.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
