How to Eliminate Null Checks in Java: Use Null Object Pattern and Best Practices
This article explains why excessive null‑checking clutters Java code, distinguishes valid versus invalid null returns, and shows how to replace them with assert statements, exceptions, empty collections, or the Null Object pattern to write cleaner, more reliable backend code.
To avoid null‑pointer calls, developers often write repetitive null‑check statements like if (someObject != null) { someObject.doCalc(); }, which leads to bulky and ugly code.
Before adding a null check, distinguish two situations:
null is a valid, meaningful return value according to the method contract. null is an invalid response and should be treated as an error.Case 2 – Invalid null : When null represents an unreasonable argument (e.g., a required API parameter is missing), the method should abort and throw an error. Better alternatives to explicit null checks are:
Use assert with a descriptive message to stop execution and report the problem.
Throw a NullPointerException directly, making the issue explicit.
Case 1 – Valid null : Null may legitimately indicate “no result”, such as a database query that finds nothing. Practical recommendations:
If a method returns a collection, return an empty collection instead of null, allowing callers to safely call methods like list.size() without additional checks.
If the return type is not a collection, return a neutral “empty object” rather than null.
Example of applying the Null Object pattern:
public interface Action { void doSomething(); } public interface Parser { Action findAction(String userInput); }Implementation that never returns null:
public class MyParser implements Parser {
private static final Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if (/* we can't find any actions */) {
return DO_NOTHING;
}
// return the found action
}
}Calling code becomes concise because findAction never yields null:
ParserFactory.getParser().findAction(someInput).doSomething();Additional tips:
Prefer calling "bar".equals(foo) to avoid a possible NullPointerException when foo might be null.
Java 8 and Guava provide Optional to encapsulate potentially absent values, reducing explicit null checks.
If a method truly needs to return null, reconsider whether throwing an exception would be more appropriate.
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
