Avoid Null Pointer Chaos: When to Use Null Checks vs Null Object Pattern
This article explains why excessive null‑checking in Java code is problematic, distinguishes between cases where null is a valid response and where it signals an error, and shows how returning empty collections or applying the Null Object pattern can eliminate redundant checks.
Problem
Developers often write code like if (someObject != null) { someObject.doCalc(); } to avoid NullPointerExceptions, resulting in many repetitive and ugly null‑checks. The question is whether this practice is overused and how to reduce it.
Key Answer
First, differentiate two situations:
Null is a valid, meaningful return value.
Null is an invalid response and should be treated as an error.
Case 2: Null as an Invalid Response
When null indicates a wrong or missing argument (e.g., a required API parameter), the method should abort and throw an exception. Two better alternatives to explicit null checks are:
Use assert with an explanatory message.
Throw a NullPointerException (or a custom exception) directly.
Case 1: Null as a Valid Response
Sometimes null represents an empty result, such as a database query that finds no matching rows. In this case, avoid returning null:
If the method returns a collection, return an empty collection instead of null.
If the method returns a single object, return a neutral "empty" object using the Null Object pattern.
Practical Recommendations
Example of 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 action */) {
return DO_NOTHING;
}
// return actual action
}
}Using this approach, client code can safely call:
ParserFactory.getParser().findAction(someInput).doSomething();without any null checks.
Comparison
Redundant style:
Parser parser = ParserFactory.getParser();
if (parser == null) { /* handle error */ }
Action action = parser.findAction(input);
if (action == null) { /* handle error */ } else { action.doSomething(); }Streamlined style (with Null Object):
ParserFactory.getParser().findAction(input).doSomething();Other Helpful Tips
Prefer calling "constant".equals(variable) to avoid accidental NullPointerExceptions.
Java 8 and Guava provide Optional to encapsulate potentially absent values.
If a method might 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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
