Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 57 ยท Behavioral Patterns

Null Object Pattern

Learn the Null Object pattern: replace null with a do-nothing object that shares the interface, remove scattered null checks, and know when this hides real errors.

Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake". Every method that might return null hands its caller a hidden duty: check before use. Forget once and the program crashes with a NullPointerException, a TypeError or a segmentation fault, usually far from where the null came from.

The Null Object pattern removes the duty. Instead of returning null for "nothing here", you return a real object that implements the same interface and behaves as "nothing" in a safe, well-defined way. Callers use it exactly like any other object, so there is no if (x != null) in sight. It was sketched in the pattern literature by Bobby Woolf and is a close cousin of polymorphism: the "no object" case becomes one more implementation of the interface.

The problem in code

Here is the usual shape of the trouble. A service accepts an optional logger, and the code is full of guards:

JavaScript
class Checkout {
  constructor(logger) { this.logger = logger; }   // may be null
  pay(amount) {
    if (this.logger) this.logger.log("paying " + amount);
    // ... more work ...
    if (this.logger) this.logger.log("paid");
  }
}

Each new log line needs its own guard, and one missing guard means a crash for every caller who passed no logger. The null checks are also noise: they have nothing to do with taking payments.

The solution: a do-nothing implementation

classDiagram
    class Logger {
        <<interface>>
        +log(message)
    }
    class ConsoleLogger
    class NullLogger
    Logger <|.. ConsoleLogger
    Logger <|.. NullLogger
    Checkout --> Logger

Checkout depends on Logger; NullLogger is one more implementation whose log does nothing.

The participants are:

  • Abstract type (Logger): the interface, written explicitly in Java or C#, implied in JavaScript or Python.
  • Real object (ConsoleLogger): the useful behavior.
  • Null object (NullLogger): same methods, harmless behavior.
  • Client (Checkout): works with the abstract type and never checks for null.
JS A logger that does nothing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Checkout.pay has no conditional at all. The decision "log or not" was made once, where the object was created, and the rest of the code is oblivious. That is the real value of the pattern: it moves a decision from many use sites to one construction site.

A real/null pair that returns values

A null object can also return neutral values. For an operation that returns something, choose a result that is safe: zero, an empty list, an empty string, or a "guest" with no permissions. The next example shows a user lookup where the null object is a guest.

JS A guest user instead of null

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last lines show the cheapest and most common null object of all: the empty collection. A method that returns an empty list instead of null lets callers loop without a guard. Java's Collections.emptyList(), Optional.empty() and an empty String follow the same idea.

A null object that adds the missing behavior

Sometimes the null object needs to respond to more than silence. Think of a shopping cart discount: a customer with no coupon should simply pay full price, and the code that computes totals should not ask whether a coupon exists.

JS No coupon, full price

Press Run (or Ctrl + Enter) to see the console output here.

No output.

NoCoupon.apply returns its input unchanged, the neutral element, like adding zero or multiplying by one.

When not to use it

The pattern is not a cure for every missing value. Be careful in these cases:

  • Hiding real errors. If a record must exist, such as the order for a payment that is being processed, a quiet stand-in lets the program carry on with wrong data. A missing required record should throw or return an explicit error.
  • The caller needs to know. If "not found" changes what the user should see (a 404 page, a validation message), the caller has to find out. Return Optional, a result type, or expose an isNull/isGuest flag, as GuestUser does above.
  • Silent behavior surprises. A NullLogger is fine. A NullPaymentGateway that "succeeds" without charging anyone is a disaster. Do-nothing must be a sensible, expected behavior.
  • Interfaces with many methods. Writing a null version of a 30-method interface is tedious. Consider a smaller interface (see Interface Segregation).

Languages also offer their own tools: Optional in Java, nullable types in Kotlin, Swift, C# and TypeScript, and the Maybe or Option types of functional languages. These make "might be missing" part of the type, so the compiler reminds callers. Null Object is the object-oriented answer, and the type-system tools are the other answer; they combine well, for example optional.orElse(NullLogger).

A related design is the State pattern, where a "no state" or "idle" state object can play the role of the null object, and the Strategy pattern, where a "do nothing" strategy is a null strategy.

A null object is usually stateless and immutable, so a single shared instance (the GUEST and NO_COUPON constants above) is enough. That makes it a legitimate, safe use of the Singleton idea, because there is nothing in it to share badly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of the Null Object pattern?

    The decision about 'no object' is made once, where the object is created, so the rest of the code needs no null checks.
  2. 2. Which is the simplest, most common null object?

    Returning an empty list lets callers loop with no guard. It is a null object for collections.
  3. 3. When is a Null Object a bad idea?

    Do-nothing must be a safe, expected behavior. A fake success for payments hides a real problem.
  4. 4. What should a NoCoupon null object's apply(total) return?

    The neutral behavior for 'no discount' is to leave the total as it is, so the caller's code works without a special case.

Summary

  • A Null Object is a real implementation of an interface whose behavior means "nothing here", so callers never check for null.
  • It moves the null decision from every use site to the single place where the object is chosen.
  • Choose neutral behavior: do nothing, return empty collections, zero, unchanged values or a guest with no rights.
  • Null objects are normally stateless, so one shared instance is enough.
  • Do not use it to hide errors or when the caller needs to know the value is missing; use exceptions, Optional or result types there.

Next lesson: Repository and Unit of Work.