Skip to content

Introduce Special Case: Replace Repeated Null Checks With an Object

Learn how to replace scattered null checks with a special-case object that carries sensible defaults, with step-by-step code in TypeScript, Python and PHP.

9 min readRefactoring

Introduce Special Case replaces repeated checks for a missing or unusual value with an object that stands in for it. The object answers the same questions as the real thing, using defaults that callers would otherwise hard-code at every check. When the special case means "nothing is here", the object is usually called a Null Object. This guide uses a desk-booking system for a coworking space called Harbor Desk. Each desk may have a member assigned to it. When nobody is assigned, the desk is a hot desk, and several parts of the codebase each handle that case on their own. You will move that knowledge into a single UnassignedMember class, in small steps that keep the tests green.

The problem

A situation where the obvious design starts to hurt.

In Harbor Desk, Desk.member is either a Member or null. Every function that touches a desk starts by checking for null. The label code falls back to "hot desk", the billing code to a 0% discount, and the locker planner to zero lockers. The same question, "is anyone assigned?", is asked four times with four slightly different answers spread across the file.

Say the business decides hot desks get one shared locker, or the label should read "open seat". You then have to find every null check and update it, and missing one leads to a bug that only appears for empty desks. The checks also bury the real logic of each function under defensive branching. In an interview, this is the kind of code where a reviewer asks: what happens if a fifth function forgets the check?

Before and after

The same code, before and after the change.

Before

class Member {
  constructor(
    readonly name: string,
    readonly discountPercent: number,
    readonly lockers: number,
  ) {}
}

class Desk {
  constructor(readonly code: string, readonly member: Member | null) {}
}

function deskLabel(desk: Desk): string {
  if (desk.member === null) {
    return `${desk.code}: hot desk`;
  }
  return `${desk.code}: ${desk.member.name}`;
}

function monthlyCharge(desk: Desk, baseRate: number): number {
  const discount = desk.member === null ? 0 : desk.member.discountPercent;
  return (baseRate * (100 - discount)) / 100;
}

function lockersToPrepare(desks: Desk[]): number {
  let total = 0;
  for (const desk of desks) {
    if (desk.member !== null) {
      total += desk.member.lockers;
    }
  }
  return total;
}

function freeDeskCount(desks: Desk[]): number {
  return desks.filter((desk) => desk.member === null).length;
}

const desks = [
  new Desk("A1", new Member("Priya Nair", 15, 2)),
  new Desk("A2", null),
];
for (const desk of desks) {
  console.log(deskLabel(desk), monthlyCharge(desk, 320));
}
console.log(lockersToPrepare(desks), freeDeskCount(desks));

After

class Member {
  constructor(
    readonly name: string,
    readonly discountPercent: number,
    readonly lockers: number,
  ) {}

  get isUnassigned(): boolean {
    return false;
  }
}

class UnassignedMember extends Member {
  constructor() {
    super("hot desk", 0, 0);
  }

  override get isUnassigned(): boolean {
    return true;
  }
}

const UNASSIGNED: Member = Object.freeze(new UnassignedMember());

class Desk {
  readonly member: Member;

  constructor(readonly code: string, member: Member | null) {
    this.member = member ?? UNASSIGNED;
  }
}

function deskLabel(desk: Desk): string {
  return `${desk.code}: ${desk.member.name}`;
}

function monthlyCharge(desk: Desk, baseRate: number): number {
  return (baseRate * (100 - desk.member.discountPercent)) / 100;
}

function lockersToPrepare(desks: Desk[]): number {
  let total = 0;
  for (const desk of desks) {
    total += desk.member.lockers;
  }
  return total;
}

function freeDeskCount(desks: Desk[]): number {
  return desks.filter((desk) => desk.member.isUnassigned).length;
}

const desks = [
  new Desk("A1", new Member("Priya Nair", 15, 2)),
  new Desk("A2", null),
];
for (const desk of desks) {
  console.log(deskLabel(desk), monthlyCharge(desk, 320));
}
console.log(lockersToPrepare(desks), freeDeskCount(desks));

Why it's worth it

What the change buys you.

The defaults for an empty desk (the label text, a 0% discount, no lockers) now live in one class. Every caller gets them by calling the same methods it already uses for real members. Polymorphism replaces the branching. Each function now reads as what it does, not as a list of guard clauses, and a new function that reads desk.member.lockers handles hot desks correctly without its author having to remember them.

The outputs are unchanged. For Priya's desk the label is A1: Priya Nair and the charge is 272. For the hot desk the label is A2: hot desk and the charge is the full 320. The lockers total is still 2 and the free-desk count is still 1. The difference is in where the knowledge lives. If hot desks later get a shared locker, you change one number in UnassignedMember.

Not every check disappears. freeDeskCount really does need to know whether a desk is empty, so it asks isUnassigned directly. That is the honest version of the old null check. It states the business question instead of a fact about memory. The aim is to remove checks whose only job was to supply a default, not to hide the special case from the code that has to reason about it.

  • The defaults for a missing member are defined once, so changing hot-desk behaviour is a one-line edit.
  • Callers lose their guard clauses and read as straight-line business logic.
  • New code that reads desk.member cannot crash on null and gets correct hot-desk behaviour without extra effort.
  • Code that genuinely cares about empty desks asks a named domain question, isUnassigned, instead of comparing with null.
  • The type of Desk.member becomes non-nullable, so the compiler or static analyser stops flagging every access.

Careful with

  • Share the special-case instance only if it is immutable. TypeScript uses Object.freeze and PHP uses readonly properties. The Python version relies on convention, so use a frozen dataclass or __slots__ with properties if callers might assign to attributes.
  • Only move a default into the special case if every caller agrees on it. If billing wants 0 but reporting wants "unknown", keep that one check explicit rather than baking in a value that is wrong for someone.
  • Do not use a Null Object to hide data that must be present. If a desk that is marked as booked has no member, that is a bug, and raising an error is better than quietly showing "hot desk".
  • Watch persistence and serialization. Make sure the special instance is written back as null or an empty foreign key, not as a fake member row called "hot desk".

Step by step

Small, safe steps, with the tests passing after each.

  1. Write characterization tests for deskLabel, monthlyCharge, lockersToPrepare and freeDeskCount, covering a desk with a member and a desk with null. Run them and confirm they pass.

  2. Add an isUnassigned property or method to Member that returns false. Nothing calls it yet, so the tests still pass.

  3. Create UnassignedMember as a subclass of Member. Its constructor passes the defaults the callers currently hard-code ("hot desk", 0, 0), and it overrides isUnassigned to return true. Create one shared, immutable instance.

  4. Add a temporary helper isUnassigned(member) that returns true when member is null or when member.isUnassigned is true. Replace every desk.member === null check with a call to this helper. Run the tests.

  5. Change the Desk constructor to store the shared UNASSIGNED instance whenever it receives null, and tighten the field type to Member. The helper handles both forms, so the tests stay green.

  6. Inline the helper. Since desk.member can no longer be null, replace each call with desk.member.isUnassigned and delete the helper. Run the tests.

  7. Go through the callers one at a time. Wherever the special-case branch just returns the value the special object already provides, delete the conditional: first the label, then the charge, then the locker count. Run the tests after each deletion.

  8. Keep explicit isUnassigned checks only where the caller really needs to distinguish empty desks, such as freeDeskCount. Review the remaining callers to confirm none still compare member with null.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

What is the difference between a Null Object and a Special Case?

A Null Object is a special case for "nothing here". It usually does nothing or returns neutral values such as 0 or an empty list. Special Case is the broader idea: any recurring unusual value, such as an unknown customer, a guest user or an expired plan, can get its own object with its own behaviour. UnassignedMember is a Null Object because it represents the absence of a member.

Why not just use optional chaining like `desk.member?.lockers ?? 0`?

Optional chaining makes each check shorter, but every caller still decides the default on its own. You still have to remember the check everywhere, and two callers can still disagree. A special-case object puts that decision in one place and lets the type system treat the field as always present.

When should I not introduce a special case?

Skip it when only one or two callers check the value, or when each caller needs a different default. Skip it too when absence signals an error that should stop the program. In those cases an explicit check, or an exception at the point where data is loaded, says more than a silent default.

Should the special-case class extend the real class or share an interface?

Either works. Subclassing is the smallest change when the real class is simple and has no side effects in its constructor, as here. If Member loads data, validates input or has many methods, define a MemberLike interface that both classes implement. That way the special case does not inherit behaviour it should not have.

How would I explain this refactoring in an interview?

Point to the repeated null checks and name the cost: a new caller can forget the check, and a change to the default means editing several files. Then describe the fix. You move the defaults into an object that callers treat like a real one, substitute it where the value is created, and keep an explicit isUnassigned query for the code that truly needs to tell the cases apart. Mention immutability and persistence as the main risks.