Video in progress

Strong Middle 🧱 OOP and SOLID

What is the Null Object pattern and how does it differ from `Optional`?

A Null Object is an object that "does nothing" but fully matches the interface: instead of a null check, it supplies the behavior itself. Optional openly tells the caller that a value may be absent and leaves the decision to them.

📖 Answer

A Null Object example, a discount:

public interface Discount {
    Money apply(Money price);

    Discount NONE = price -> price; // null object
}

class Checkout {
    Money total(Cart cart, Discount discount) {
        return discount.apply(cart.subtotal()); // no if (discount != null)
    }
}

Discount d = promoRepo.findActive(code).orElse(Discount.NONE);

Here "no discount" is a real, meaningful state and its behavior is clear: the price doesn't change. Not every caller has to write an if.

When Optional is right: when in the "absent" case the caller has to do something different. userRepo.findByEmail(email): if nothing is found, register the user or return a 404. Building a Null User here would be a mistake: what would NullUser.getId() return? Such an object could even end up written to the database.

A short rule:

  • the absent case has a "neutral behavior" (log nothing, give no discount, an empty list): Null Object;
  • the absent case is its own business branch: Optional.

An empty collection is also the most common kind of Null Object: return List.of() from a method, not null. And Optional<List<...>> is almost always unnecessary.