Fundamentals 6 min read

Avoiding Null Checks in Java: Assertions, Exceptions, and the Null Object Pattern

This article explains how to distinguish between valid and invalid null returns in Java, recommends using assertions or exceptions for erroneous nulls, suggests returning empty collections or objects, and demonstrates the Null Object pattern with code examples to eliminate repetitive null‑pointer checks.

Top Architect
Top Architect
Top Architect
Avoiding Null Checks in Java: Assertions, Exceptions, and the Null Object Pattern

In Java development, null‑pointer checks are ubiquitous, but they often lead to verbose and fragile code.

Two situations should be distinguished: (1) null is a meaningful, valid response, and (2) null indicates an invalid argument that should abort execution.

For the second case, use assertions or throw a NullPointerException to signal the error explicitly.

For the first case, prefer returning empty collections or empty objects instead of null, and consider the Null Object pattern to avoid null checks entirely.

Example of the Null Object pattern:

public class MyParser implements Parser {
    private static 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;
        }
    }
}

Using this approach, client code can be simplified from repetitive null checks:

ParserFactory.getParser().findAction(someInput).doSomething();

Additional recommendations include using the safe equals form "bar".equals(foo) , leveraging Java 8/Guava Optional , or throwing an exception instead of returning null.

JavaException HandlingBest PracticesAssertionsNull Object patternnull checks
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.