LLD

Behavioral Patterns

Null Object pattern

When a collaborator is often missing, every caller ends up checking for null, and one forgotten check is a crash. We build a food order's bill twice, once with null for a missing plan or coupon and once with objects that stand for none, and look at when such an object hides a real bug.

A food delivery app bills every order the same way. It adds the delivery fee, takes off any coupon, and prints a few notes under the total. Some customers pay for a Gold plan that makes delivery free, and many do not. Some type a coupon code, and others leave the box empty. So the bill code keeps running into the same question: does this customer have a plan, and did they enter a code?

The same question shows up wherever a collaborator is optional: a logger that may be switched off, a notification setting the user turned off, a parking lot without a display board, a game piece with no special power. In each case the obvious code passes null for "none" and checks for it everywhere.

The Null Object pattern replaces that null with a real object that stands for "none". It answers every question with a harmless value, so callers stop checking. In this article we build an order's bill twice. The first version uses null for a missing plan or coupon. The second gives every customer a membership and every order a coupon, even when that is "none". Then we look at the danger in the pattern: an object that quietly does nothing can hide a mistake that should have been an error.

All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the version with null, the rest from the finished design. Both programs run, and the outputs shown are what they print.

The order we are building

All amounts are in cents. The bill must do five things:

  1. Add a delivery fee of $4 to the items total.
  2. Make delivery free for Gold members on orders of $20 or more. Below that, tell them how much more to add.
  3. Tell a customer whose Gold plan has ended what renewing would save.
  4. Apply a coupon if the customer entered one. SAVE20 takes 20% off orders of $25 or more, up to $10.
  5. When the order is placed, add the delivery saving to the member's running total, which the app shows as "you saved $X with Gold".
Same questions, different answers
The top grid shows what each kind of membership answers when the order asks for the delivery fee on $4, for notes, and to record a saving. The bottom grid does the same for a coupon. The rows marked NONE answer with the full fee, an empty list, nothing recorded and nothing off, and NONE refuses a negative saving just as Gold does. They are yellow because in the finished code they are enums.The top grid shows what each kind of membership answers when the order asks for the delivery fee on $4, for notes, and to record a saving. The bottom grid does the same for a coupon. The rows marked NONE answer with the full fee, an empty list, nothing recorded and nothing off, and NONE refuses a negative saving just as Gold does. They are yellow because in the finished code they are enums.
The order asks every membership and every coupon the same questions. The top grid shows what each kind of membership answers when the order asks for the delivery fee on $4, for notes, and to record a saving. The bottom grid does the same for a coupon. The rows marked NONE answer with the full fee, an empty list, nothing recorded and nothing off, and NONE refuses a negative saving just as Gold does. They are yellow because in the finished code they are enums.

Read the grid one row at a time. A Gold member, a member whose plan has ended and a customer with no plan all face the same three questions. Only the answers differ. The "none" rows are not blank: they have real answers, and those answers are the full fee, no notes and nothing off. That is the idea the whole pattern rests on, so it is the thing to draw first in an interview.

The first version: null for "none"

The obvious code keeps a GoldPlan field that is null when the customer has no plan, and a PercentCoupon field that is null when no code was entered. The bill checks both:

Order.javalines 28–58 of 69
    public Bill bill() {        int deliveryFee = baseDeliveryFee;        List<String> notes = new ArrayList<>();        if (plan != null && plan.isActiveOn(today)) {            if (itemsTotal >= GoldPlan.FREE_DELIVERY_FROM) {                deliveryFee = 0;                notes.add("Gold: free delivery, you save " + Dollars.format(baseDeliveryFee));            } else {                notes.add("Gold: add " + Dollars.format(GoldPlan.FREE_DELIVERY_FROM - itemsTotal) + " more for free delivery");            }        } else if (plan != null) {            String ended = "Gold ended on " + DAY.format(plan.validUntil()) + ". ";            if (itemsTotal >= GoldPlan.FREE_DELIVERY_FROM) {                notes.add(ended + "Renew to save " + Dollars.format(baseDeliveryFee) + " on this order");            } else {                notes.add(ended + "Renew for free delivery from " + Dollars.format(GoldPlan.FREE_DELIVERY_FROM));            }        }        int discount = 0;        if (coupon != null) {            discount = coupon.discount(itemsTotal);            if (itemsTotal < coupon.minItemsTotal()) {                notes.add(coupon.code() + " needs " + Dollars.format(coupon.minItemsTotal()) + ". Add "                        + Dollars.format(coupon.minItemsTotal() - itemsTotal) + " more");            } else {                notes.add(coupon.code() + ": " + coupon.percent() + "% off, you save " + Dollars.format(discount));            }        }        int total = itemsTotal + deliveryFee - discount;        return new Bill(itemsTotal, deliveryFee, discount, total, notes);    }

The highlighted lines are the checks. The first asks whether there is a plan and it is still active. The second catches a plan that has ended. The third asks whether there is a coupon. Each check guards the code that uses the field.

This works, and for one optional field read in one method it is fine. Then a new feature arrives. The app wants to show members how much Gold has saved them, so place() records the saving:

Order.javalines 60–68 of 69
    public Bill place() {        if (placed) {            throw new IllegalStateException("order " + id + " is already placed");        }        Bill bill = bill();        plan.recordSaving(baseDeliveryFee - bill.deliveryFee());        placed = true;        return bill;    }

Line 65 has no check. The person who added it was thinking about members, because only members have savings. The demo places three orders: Asha has Gold, Ravi has no plan, and Meera's plan has ended.

$ java Main
bill: $32 [Gold: free delivery, you save $4]
  placed
bill: $40 [SAVE20: 20% off, you save $9]
  place() failed: Cannot invoke "GoldPlan.recordSaving(int)" because "this.plan" is null
bill: $29 [Gold ended on 12 Nov 2026. Renew to save $4 on this order]
  placed

The demo printed Ravi's $40 bill, so a customer would already have seen it. Then place() threw a NullPointerException, and the order was not placed. Nothing in the compiler pointed at line 65.

Every reader of the field must remember the check. bill() has three checks and place() needs one more. A receipt, a weekly savings email or an invoice that uses the plan later needs its own checks too.

A missed check fails for the customers who have nothing. Every Gold member's order works. The crash only shows up for customers without a plan, who may be most of the customers.

The rules for "none" are spread out. What a customer without a plan pays is written as "skip this block" in several places. No line of code says it directly.

Checks in every method
The first version's Order. In bill(), the three amber lines check for a missing plan, an ended plan and a missing coupon. In place(), the red line calls recordSaving on the plan with no check, so the order of a customer without a plan throws after their bill has been shown. A new method that reads plan or coupon needs its own checks.The first version's Order. In bill(), the three amber lines check for a missing plan, an ended plan and a missing coupon. In place(), the red line calls recordSaving on the plan with no check, so the order of a customer without a plan throws after their bill has been shown. A new method that reads plan or coupon needs its own checks.
Three checks in bill(), and none in the method added later. The first version's Order. In bill(), the three amber lines check for a missing plan, an ended plan and a missing coupon. In place(), the red line calls recordSaving on the plan with no check, so the order of a customer without a plan throws after their bill has been shown. A new method that reads plan or coupon needs its own checks.

The idea

The pattern works like this:

  • Each optional collaborator gets an interface: Membership and Coupon.
  • The real kinds implement it: GoldMembership, PercentCoupon.
  • One more class implements it for "none". Its methods return the neutral answer for each question (the full fee, an empty list, zero) or do nothing.
  • The field is never null. A customer without a plan holds the "none" membership, and the order calls it like any other.

The "none" class is called the null object. Calling one of its methods is always safe, and the answer is the one a caller would have written in the else branch of a null check.

Building it, step by step

Step 1: ask the question the caller has

The order needs three things from a membership: the delivery fee, the notes to print, and somewhere to record a saving. Those become the interface:

perk/Membership.javalines 5–22 of 22
/** What a customer's plan does to an order. Every customer has one, even without a plan. */public interface Membership {    /** The one shared answer for every customer without a plan. */    Membership NONE = NoMembership.INSTANCE;     int deliveryFee(int baseFee, int itemsTotal);     List<String> notes(int baseFee, int itemsTotal);     void recordSaving(int cents);     /** The rule each of our memberships applies to a saving, including the ones that record nothing. */    static void requireValidSaving(int cents) {        if (cents < 0) {            throw new IllegalArgumentException("a saving cannot be negative: " + cents);        }    }}

Line 8 is the shared "none" object, which we come to in Step 2. Line 17 is the rule each of our three memberships applies to a saving, and Step 2 shows why even "none" applies it. Each method is a question with an answer for every kind of membership, including none. That was not true of the first version's fields. Its bill() read plan.validUntil() on line 39 to print when a plan ended, and a customer without a plan has no end date.

Decision

What does the null object answer when there is no neutral value?

Return null

validUntil() on the "none" object returns null. Every caller that uses the date now needs a null check again, which is the problem the pattern was meant to remove.

Throw UnsupportedOperationException

The method exists on the interface but fails for one kind. The compiler cannot see which calls are safe, so this is the first version's crash with a better message.

Return a made-up value

validUntil() returns LocalDate.MAX or the day the app launched. The code runs, and a note that prints the date shows "31 Dec +999999999". A made-up value is a wrong answer that looks right.

Ask a different questionOur pick

The order never needed the date. It needed the lines to print. notes() returns them, and "none" has an honest answer: an empty list. The end date stays on GoldMembership, where code that has a Gold plan in hand can read it. The cost is that each membership writes its own text, so a change to the wording of the notes touches each class that writes them.

Step 2: one "none" object for everyone

Here is the null object for memberships:

perk/NoMembership.javalines 5–24 of 24
/** No plan: the full delivery fee, nothing to print and nothing to record. */enum NoMembership implements Membership {    INSTANCE;     @Override    public int deliveryFee(int baseFee, int itemsTotal) {        return baseFee;    }     @Override    public List<String> notes(int baseFee, int itemsTotal) {        return List.of();    }     @Override    public void recordSaving(int cents) {        Membership.requireValidSaving(cents);        // A customer without a plan has no savings to track.    }}

Each method gives the neutral answer for its own question. deliveryFee returns the fee it was given, unchanged. notes returns an empty list, not null, so the order can add it to the bill without a check. recordSaving records nothing, and the comment on line 22 says why. Before that, line 21 refuses a negative saving, exactly as GoldMembership does. A null object must refuse what the real classes refuse. If NONE accepted -$50 while Gold threw, a bug that produced it would fail only for Gold members.

NoMembership is an enum with one constant, and it is not public. Code outside the perk package reaches it only as Membership.NONE. The coupon side is the same shape: NoCoupon returns 0 off and no notes, and callers use Coupon.NONE.

Decision

How many NoMembership objects should there be?

A plain class, created wherever it is needed

NoMembership is an ordinary class, and new NoMembership() appears wherever a customer has no plan. This works, because the object holds nothing. It allocates an object for every such customer for no reason, and it invites code like membership instanceof NoMembership, which is a null check with a longer name.

One shared constantOur pick

The object holds no state of its own, so one object can serve every customer and every thread at once. An enum makes the single object Java's job. Keeping the enum package-private and exposing Membership.NONE keeps callers on the interface. The cost is small: every caller sees one name, NONE, and has to know it exists.

Step 3: the order stops checking

With every field set, the order asks its questions directly:

order/Order.javalines 36–53 of 62
    public Bill bill() {        int deliveryFee = membership.deliveryFee(baseDeliveryFee, itemsTotal);        int discount = coupon.discount(itemsTotal);        List<String> notes = new ArrayList<>(membership.notes(baseDeliveryFee, itemsTotal));        notes.addAll(coupon.notes(itemsTotal));        int total = Math.subtractExact(Math.addExact(itemsTotal, deliveryFee), discount);        return new Bill(itemsTotal, deliveryFee, discount, total, notes);    }     public Bill place() {        if (placed) {            throw new IllegalStateException("order " + id + " is already placed");        }        Bill bill = bill();        membership.recordSaving(baseDeliveryFee - bill.deliveryFee());        placed = true;        return bill;    }

Compare this with the first version. There is no if about the plan or the coupon. Line 37 asks the membership for the fee, and Gold, an ended plan and NONE each answer. Line 50 records the saving, and for Ravi it is NONE.recordSaving(0), which does nothing. The crash from the first version cannot happen here, because there is no null to call.

placed is set after recordSaving returns. If recording throws, the order is not marked placed and the caller can try again.

The pattern only works if null cannot get in. The constructor refuses it, and the message names what to use instead:

order/Order.javalines 22–34 of 62
    public Order(String id, int itemsTotal, int baseDeliveryFee, Membership membership, Coupon coupon) {        this.id = Objects.requireNonNull(id, "id");        if (itemsTotal <= 0) {            throw new IllegalArgumentException("items total must be positive: " + itemsTotal);        }        if (baseDeliveryFee < 0) {            throw new IllegalArgumentException("delivery fee cannot be negative: " + baseDeliveryFee);        }        this.itemsTotal = itemsTotal;        this.baseDeliveryFee = baseDeliveryFee;        this.membership = Objects.requireNonNull(membership, "membership: use Membership.NONE for a customer without a plan");        this.coupon = Objects.requireNonNull(coupon, "coupon: use Coupon.NONE when no code was entered");    }

This is a message for a programmer, not a customer. A null here means some code forgot the rule, and failing in the constructor puts the error next to the mistake, not deep inside place().

Step 4: a plan that ended is not "no plan"

Meera paid for Gold until 12 November. On 21 November she has no benefits, so NONE would give her the right fee. But it would tell her nothing, and the app wants to tell her what renewing would save. Her case gets its own class:

perk/ExpiredMembership.javalines 21–39 of 40
    @Override    public int deliveryFee(int baseFee, int itemsTotal) {        return baseFee;    }     @Override    public List<String> notes(int baseFee, int itemsTotal) {        String ended = "Gold ended on " + DAY.format(endedOn) + ". ";        if (itemsTotal >= GoldMembership.FREE_DELIVERY_FROM) {            return List.of(ended + "Renew to save " + Dollars.format(baseFee) + " on this order");        }        return List.of(ended + "Renew for free delivery from " + Dollars.format(GoldMembership.FREE_DELIVERY_FROM));    }     @Override    public void recordSaving(int cents) {        Membership.requireValidSaving(cents);        // An ended plan saves nothing, so there is nothing to add.    }

The fee is the full fee, and recordSaving checks the amount and records nothing, just like NONE. The notes are different: an ended plan has something to say. An object like this, which stands for one particular unusual situation and has behaviour of its own, is often called a special case. A null object is the special case for "nothing here".

Something has to decide which membership a customer gets. That is Members:

perk/Members.javalines 35–43 of 58
    public Membership membershipOf(String customerId) {        requireKnown(customerId);        GoldMembership plan = plans.get(customerId);        if (plan == null) {            return Membership.NONE;        }        LocalDate today = LocalDate.now(clock);        return plan.isActiveOn(today) ? plan : new ExpiredMembership(plan.validUntil());    }

For a known customer, the method has three answers. No plan returns NONE on line 39. An active plan returns the customer's own GoldMembership, the same object on every order, so its savings add up. An ended plan returns an ExpiredMembership with the end date. "Today" comes from the Clock passed into Members, so the demo, and any test, can fix the date.

GoldMembership itself does not look at the date. An ended plan passed straight to an Order would still give free delivery. So its constructor is package-private and addGold returns nothing: code outside the perk package gets a Gold plan only from membershipOf, which checks the date first.

Decision

Should an ended plan be NONE?

Return NONE

The fee is right and there is one fewer class. But the customer loses the renewal note, and nothing in the code records that the plan ended. If a later rule treats ended plans differently, for example a cheaper renewal price, there is no place to put it.

Its own class, ExpiredMembershipOur pick

The ended plan says what it is, and the order still calls it without a check. The cost is one more class that repeats NONE's fee and saving answers. We accept the repetition because the two classes stand for different situations, and they can change separately.

Renewing is out of scope for this page. addGold refuses a second plan, so a real app would add a renew method to Members that replaces the stored plan. From the next order, membershipOf would return Gold again, and Order would not change.

Step 5: absent on purpose, or a mistake?

The danger in this pattern is in deciding when to use the null object. "No code entered" and "a code we do not have" both end with no coupon, but they are not the same thing. If Ravi types SAVE2O with a capital O on his $45 order and the app quietly uses Coupon.NONE, he pays $9 more and believes he got the discount.

Coupons.forCode keeps the two apart:

perk/Coupons.javalines 25–36 of 37
    /**     * Coupon.NONE when the box was left empty, the coupon when the code is     * known, and empty when the customer typed a code we do not have.     */    public Optional<Coupon> forCode(String entered) {        Objects.requireNonNull(entered, "entered");        String code = entered.strip().toUpperCase(Locale.ROOT);        if (code.isEmpty()) {            return Optional.of(Coupon.NONE);        }        return Optional.ofNullable(byCode.get(code));    }

An empty box returns Coupon.NONE on line 33: the customer chose no coupon, and "none" is the right answer. A code we know returns that coupon. A code we do not know returns an empty Optional on line 35. The caller has to handle it, and the demo turns it into a message for the customer.

Decision

What does an unknown coupon code become?

Coupon.NONE

The bill goes through at full price. The customer sees no error and no discount, and the typo becomes a support ticket. This is how a null object hides a bug: the code did something reasonable with a value that was wrong.

An exception

forCode throws an exception for a code it does not know. This works, but a typo is something customers do every day. Using an exception for it means every caller wraps the lookup in a try, and the exception carries no more information than an empty result.

An empty OptionalOur pick

The method's return type tells the caller that a code may be missing, and the caller has to unwrap the Optional to get a coupon. Calling get() without looking would still compile and then throw, but the type makes that a visible choice. The cost is that "no code" is now Optional.of(Coupon.NONE), which is two layers of "nothing" that the comment on the method has to explain.

Customer ids follow the opposite rule. A customer id comes from a logged-in session, and every id should exist. If membershipOf is asked about an id it has never seen, that is a bug in our code, not a customer without a plan. requireKnown on line 36 throws IllegalArgumentException. Returning NONE would bill a stranger as a customer and hide the bug.

When the caller is another program, such as a partner's system sending orders with coupon codes, nobody is there to retype the code. A throw at the boundary is then the simpler shape:

Sketchnot part of the final code
Coupon couponFor(String entered) {    return coupons.forCode(entered)            .orElseThrow(() -> new IllegalArgumentException("unknown coupon: " + entered));}

Here is the rule. Use the null object when nothing is a normal answer. Use an empty Optional or an error when nothing means something went wrong.

The finished design

The finished design
Order uses the two interfaces and creates a Bill record. Three classes implement Membership: GoldMembership, ExpiredMembership and the NoMembership enum behind Membership.NONE. Two implement Coupon: PercentCoupon and the NoCoupon enum behind Coupon.NONE. Members creates and owns the Gold plans, and creates an ExpiredMembership when a plan has ended. Coupons owns the coupons on offer, fixed when it is built. Each class lists its fields and its public methods, apart from the interface methods it implements. Dollars, which only formats amounts, is left out.Order uses the two interfaces and creates a Bill record. Three classes implement Membership: GoldMembership, ExpiredMembership and the NoMembership enum behind Membership.NONE. Two implement Coupon: PercentCoupon and the NoCoupon enum behind Coupon.NONE. Members creates and owns the Gold plans, and creates an ExpiredMembership when a plan has ended. Coupons owns the coupons on offer, fixed when it is built. Each class lists its fields and its public methods, apart from the interface methods it implements. Dollars, which only formats amounts, is left out.
Order holds a Membership and a Coupon, and never one that is null. Order uses the two interfaces and creates a Bill record. Three classes implement Membership: GoldMembership, ExpiredMembership and the NoMembership enum behind Membership.NONE. Two implement Coupon: PercentCoupon and the NoCoupon enum behind Coupon.NONE. Members creates and owns the Gold plans, and creates an ExpiredMembership when a plan has ended. Coupons owns the coupons on offer, fixed when it is built. Each class lists its fields and its public methods, apart from the interface methods it implements. Dollars, which only formats amounts, is left out.

Here is Ravi's order, traced through the objects:

One order, traced
The app places Ravi's $45 order (1). Order asks NONE for the delivery fee and gets the full $4 (2). It asks SAVE20 for the discount and gets $9 (3). It collects the notes, an empty list from NONE and one line from SAVE20 (4). It tells NONE to record a saving of zero, which does nothing (5). It returns a $40 bill to the app (6).The app places Ravi's $45 order (1). Order asks NONE for the delivery fee and gets the full $4 (2). It asks SAVE20 for the discount and gets $9 (3). It collects the notes, an empty list from NONE and one line from SAVE20 (4). It tells NONE to record a saving of zero, which does nothing (5). It returns a $40 bill to the app (6).
The order asks NONE the same questions it asks a Gold plan. The app places Ravi's $45 order (1). Order asks NONE for the delivery fee and gets the full $4 (2). It asks SAVE20 for the discount and gets $9 (3). It collects the notes, an empty list from NONE and one line from SAVE20 (4). It tells NONE to record a saving of zero, which does nothing (5). It returns a $40 bill to the app (6).

The whole project is below. Click any class name in the code to open that class.

orderOrder.java
package order; import java.util.ArrayList;import java.util.List;import java.util.Objects; import perk.Coupon;import perk.Membership; /** * One food order. It asks its membership about delivery and its coupon about * the discount, and never checks for either. One request owns it, so it has no lock. */public final class Order {    private final String id;    private final int itemsTotal;    private final int baseDeliveryFee;    private final Membership membership;    private final Coupon coupon;    private boolean placed;     public Order(String id, int itemsTotal, int baseDeliveryFee, Membership membership, Coupon coupon) {        this.id = Objects.requireNonNull(id, "id");        if (itemsTotal <= 0) {            throw new IllegalArgumentException("items total must be positive: " + itemsTotal);        }        if (baseDeliveryFee < 0) {            throw new IllegalArgumentException("delivery fee cannot be negative: " + baseDeliveryFee);        }        this.itemsTotal = itemsTotal;        this.baseDeliveryFee = baseDeliveryFee;        this.membership = Objects.requireNonNull(membership, "membership: use Membership.NONE for a customer without a plan");        this.coupon = Objects.requireNonNull(coupon, "coupon: use Coupon.NONE when no code was entered");    }     public Bill bill() {        int deliveryFee = membership.deliveryFee(baseDeliveryFee, itemsTotal);        int discount = coupon.discount(itemsTotal);        List<String> notes = new ArrayList<>(membership.notes(baseDeliveryFee, itemsTotal));        notes.addAll(coupon.notes(itemsTotal));        int total = Math.subtractExact(Math.addExact(itemsTotal, deliveryFee), discount);        return new Bill(itemsTotal, deliveryFee, discount, total, notes);    }     public Bill place() {        if (placed) {            throw new IllegalStateException("order " + id + " is already placed");        }        Bill bill = bill();        membership.recordSaving(baseDeliveryFee - bill.deliveryFee());        placed = true;        return bill;    }     public boolean isPlaced() {        return placed;    }     public String id() {        return id;    }}
Click a class name in the code to open its fileJava · 62 lines · 484 in the project

demo/Main.java places five orders for three customers, with the date fixed at 21 November 2026:

$ java demo.Main
A-101 asha, items $32, no code
  $32 + delivery $0 - discount $0 = $32
  Gold: free delivery, you save $4
A-102 ravi, items $45, code "save20"
  $45 + delivery $4 - discount $9 = $40
  SAVE20: 20% off, you save $9
A-103 meera, items $25, no code
  $25 + delivery $4 - discount $0 = $29
  Gold ended on 12 Nov 2026. Renew to save $4 on this order
A-104 asha, items $15, code "SAVE20"
  $15 + delivery $4 - discount $0 = $19
  Gold: add $5 more for free delivery
  SAVE20 needs $25. Add $10 more
A-105 ravi, items $45, code "SAVE2O"
  refused: there is no coupon SAVE2O. Fix the code or clear it
Asha's Gold savings so far: $4
Ravi, no plan: delivery $4 on a $10 order, notes [], savings $0
membershipOf("kiran") threw: no such customer: kiran

A-101 is Asha's Gold order of $32, so delivery is free and the note says so. A-102 is Ravi's: no plan and save20 in lower case, so he pays the $4 fee and gets $9 off. The first version threw on this order. A-103 is Meera's, and her ended plan prints the renewal note. A-104 is Asha again with $15, below both thresholds, so she gets two notes asking her to add more. A-105 has the mistyped code, and the order is refused before it is built. Asha's savings are $4, from A-101 only, because A-104 recorded a saving of zero. The next line shows what NONE answers for Ravi: the full $4 fee on a $10 order, and no notes. goldSavings reports $0 for him because he has no plan. Asking about an unknown customer throws.

One Gold plan is shared by all of one customer's orders, and two of them can be placed at the same moment from two phones. recordSaving and savedCents are synchronized, so no saving is lost. Members keeps its customers and plans in a ConcurrentHashMap, so a sign-up can arrive while orders are being billed. addGold uses putIfAbsent, so two requests adding a plan for one customer cannot both succeed. Coupons is built once from the list of offers and never changes, so any thread can read it. An Order belongs to the one request that builds and places it, so it has no lock. NONE holds no state, so all threads can share it.

What it costs

Callers get simpler, and the interface gets stricter. Order lost every if. A new caller, such as a weekly savings email, needs no checks either. In exchange, every method on Membership must have an honest answer for "none". Adding a method such as priorityDelivery() means NONE and ExpiredMembership need an answer too, and Step 1's Decision has to be made again for that method.

A null object can hide a bug. NONE is the right answer for "this customer has no plan" and the wrong answer for "we failed to load this customer's plan". If the code that loads plans returned NONE when the database call failed, every Gold member would pay for delivery and see no error. The null object has to come from a place that knows the difference, like membershipOf in Step 4.

What should a missing thing become?
Four situations from this design and the answer each one gets. No plan, or an empty coupon box, is nothing on purpose: Membership.NONE or Coupon.NONE, in yellow. A plan that has ended is there but different: ExpiredMembership, a special case. A typed code we do not have was asked for and not found: an empty Optional, refused with a message to the customer, in red. An unknown customer id is a bug: an exception, also in red.Four situations from this design and the answer each one gets. No plan, or an empty coupon box, is nothing on purpose: Membership.NONE or Coupon.NONE, in yellow. A plan that has ended is there but different: ExpiredMembership, a special case. A typed code we do not have was asked for and not found: an empty Optional, refused with a message to the customer, in red. An unknown customer id is a bug: an exception, also in red.
The null object is one of four answers. Four situations from this design and the answer each one gets. No plan, or an empty coupon box, is nothing on purpose: Membership.NONE or Coupon.NONE, in yellow. A plan that has ended is there but different: ExpiredMembership, a special case. A typed code we do not have was asked for and not found: an empty Optional, refused with a message to the customer, in red. An unknown customer id is a bug: an exception, also in red.

The empty methods are easy to misread. A reader who finds recordSaving with an empty body may think someone forgot to finish it. That is why each one carries a one-line comment.

When the pattern is too much

If one method reads an optional value once, a null check or an Optional says it more plainly than an interface and two classes:

Sketchnot part of the final code
// nickname() returns Optional<String>String greeting(User user) {    return "Hello, " + user.nickname().orElse("there");}

The pattern pays off when the same optional collaborator is used in many places, or when it has behaviour (a fee to work out, a saving to record) and not just a value. A plain value, such as a nickname or a middle name, is better as an Optional.

Null Object, Optional, Special Case or Strategy?

These four sit close together, because three of them use the same class diagram and all of them deal with "what if there is nothing?".

Null ObjectOptionalSpecial CaseStrategy
What it stands forNothing, on purposeA value that may be missingOne unusual situationOne of several ways to do a job
Does the caller checkNoYes, the type warns themNoNo
What it answersNeutral values, or does nothingNothing at all until the caller handles itIts own behaviourIts own behaviour
Example hereMembership.NONEThe result of Coupons.forCodeExpiredMembershipPercentCoupon and NoCoupon

A null object is a special case for "nothing", and it is often a strategy that happens to do nothing. Optional is different in kind: it makes the caller decide.

A short way to say it: a null object answers for the missing thing, and an Optional makes the caller answer.

In an interview

The pattern appears inside low-level design questions wherever a part is optional. A logging framework's output can be turned off, and a user can disable notifications. A shopping or food order design has discounts and loyalty plans that most orders lack. A parking lot may have no display board, and most squares in a snake and ladder game have neither. The question does not need to name the pattern.

A good order for presenting it:

  1. Notice the optional collaborator. Say that many customers have no plan, so a null field would need a check in every method that uses it.
  2. Write the interface so each question has an answer for "none". If a method has no honest neutral answer, change the method.
  3. Then say where "none" comes from. Show the one place that decides between NONE, a special case and an error.

Common mistakes:

  • Checking for the null object. if (membership == Membership.NONE) puts the null check back with a longer name. If a caller needs to know, the interface is missing a question.
  • Turning every failure into "none". A plan that failed to load, a mistyped coupon and an unknown customer are errors. Hiding them makes the bug show up later, as a wrong bill.
  • Returning null from the null object. A notes() that returns null instead of an empty list moves the crash one step further on.
  • Made-up answers. A fake date or a fake id passes through the code and appears on a receipt.
  • Leaving null possible. If the constructor still accepts null, someone will pass it, and the old crash comes back.

Summary

  • Use a null object when a collaborator is often missing and "missing" has an obvious, harmless meaning.
  • Give each method an honest neutral answer: the unchanged fee, an empty list, zero, or doing nothing. If a method has none, ask a different question.
  • Keep one shared instance when the null object holds no state, and refuse null in the constructor so it cannot come back.
  • A situation with its own behaviour, such as an ended plan, gets its own special case class.
  • Decide in one place when "none" is right. A typo, a failed lookup or an unknown id is an error, not "none".

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.