Avoiding Null Checks in Java: When to Use Assertions, Exceptions, and the Null Object Pattern
This article explains why excessive null‑checking in Java code is problematic, distinguishes valid versus invalid null returns, and presents better alternatives such as assertions, throwing exceptions, returning empty collections or objects, and applying the Null Object pattern with concrete code examples.
To prevent null‑pointer exceptions, developers often write repetitive null‑checking code like if (someobject != null) { someobject.doCalc(); } , which leads to cluttered and hard‑to‑maintain codebases.
The article first separates two scenarios: (1) when null is a meaningful, valid response, and (2) when null indicates an invalid argument that should cause the program to fail early, typically by throwing an exception or using an assert statement.
For the second case, it recommends either using assert with a clear error message or explicitly throwing a NullPointerException to signal improper usage.
When null is a legitimate “empty” value, the article suggests returning an empty collection instead of null , allowing callers to operate safely without additional checks. If the return type is not a collection, it advises returning a default empty object rather than null .
It introduces the Null Object pattern as a robust solution. Example interfaces are shown:
public interface Action { void doSomething(); }
public interface Parser { Action findAction(String userInput); }Instead of returning null from findAction , a concrete implementation provides a static DO_NOTHING object:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if (/* cannot find any actions */) {
return DO_NOTHING;
}
// otherwise return a real Action
}
}Using this pattern eliminates the need for repetitive null checks, enabling concise calls such as ParserFactory.getParser().findAction(someInput).doSomething(); without fearing a NullPointerException .
Additional tips include using "constant".equals(variable) to avoid null‑safe comparisons, leveraging Java 8/Guava Optional for nullable values, and considering throwing exceptions instead of returning null when appropriate.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.