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));from typing import Optional
class Member:
def __init__(self, name: str, discount_percent: int, lockers: int) -> None:
self.name = name
self.discount_percent = discount_percent
self.lockers = lockers
class Desk:
def __init__(self, code: str, member: Optional[Member]) -> None:
self.code = code
self.member = member
def desk_label(desk: Desk) -> str:
if desk.member is None:
return f"{desk.code}: hot desk"
return f"{desk.code}: {desk.member.name}"
def monthly_charge(desk: Desk, base_rate: float) -> float:
discount = 0 if desk.member is None else desk.member.discount_percent
return base_rate * (100 - discount) / 100
def lockers_to_prepare(desks: list[Desk]) -> int:
total = 0
for desk in desks:
if desk.member is not None:
total += desk.member.lockers
return total
def free_desk_count(desks: list[Desk]) -> int:
return sum(1 for desk in desks if desk.member is None)
if __name__ == "__main__":
desks = [Desk("A1", Member("Priya Nair", 15, 2)), Desk("A2", None)]
for desk in desks:
print(desk_label(desk), monthly_charge(desk, 320))
print(lockers_to_prepare(desks), free_desk_count(desks))<?php
class Member
{
public function __construct(
public readonly string $name,
public readonly int $discountPercent,
public readonly int $lockers,
) {}
}
class Desk
{
public function __construct(
public readonly string $code,
public readonly ?Member $member,
) {}
}
function deskLabel(Desk $desk): string
{
if ($desk->member === null) {
return "{$desk->code}: hot desk";
}
return "{$desk->code}: {$desk->member->name}";
}
function monthlyCharge(Desk $desk, float $baseRate): float
{
$discount = $desk->member === null ? 0 : $desk->member->discountPercent;
return $baseRate * (100 - $discount) / 100;
}
function lockersToPrepare(array $desks): int
{
$total = 0;
foreach ($desks as $desk) {
if ($desk->member !== null) {
$total += $desk->member->lockers;
}
}
return $total;
}
function freeDeskCount(array $desks): int
{
return count(array_filter($desks, fn(Desk $d) => $d->member === null));
}
$desks = [
new Desk('A1', new Member('Priya Nair', 15, 2)),
new Desk('A2', null),
];
foreach ($desks as $desk) {
echo deskLabel($desk), ' ', monthlyCharge($desk, 320), PHP_EOL;
}
echo lockersToPrepare($desks), ' ', freeDeskCount($desks), PHP_EOL;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));from typing import Optional
class Member:
def __init__(self, name: str, discount_percent: int, lockers: int) -> None:
self.name = name
self.discount_percent = discount_percent
self.lockers = lockers
@property
def is_unassigned(self) -> bool:
return False
class UnassignedMember(Member):
def __init__(self) -> None:
super().__init__("hot desk", 0, 0)
@property
def is_unassigned(self) -> bool:
return True
UNASSIGNED = UnassignedMember()
class Desk:
def __init__(self, code: str, member: Optional[Member]) -> None:
self.code = code
self.member: Member = member if member is not None else UNASSIGNED
def desk_label(desk: Desk) -> str:
return f"{desk.code}: {desk.member.name}"
def monthly_charge(desk: Desk, base_rate: float) -> float:
return base_rate * (100 - desk.member.discount_percent) / 100
def lockers_to_prepare(desks: list[Desk]) -> int:
total = 0
for desk in desks:
total += desk.member.lockers
return total
def free_desk_count(desks: list[Desk]) -> int:
return sum(1 for desk in desks if desk.member.is_unassigned)
if __name__ == "__main__":
desks = [Desk("A1", Member("Priya Nair", 15, 2)), Desk("A2", None)]
for desk in desks:
print(desk_label(desk), monthly_charge(desk, 320))
print(lockers_to_prepare(desks), free_desk_count(desks))<?php
class Member
{
public function __construct(
public readonly string $name,
public readonly int $discountPercent,
public readonly int $lockers,
) {}
public function isUnassigned(): bool
{
return false;
}
}
final class UnassignedMember extends Member
{
private static ?self $instance = null;
private function __construct()
{
parent::__construct('hot desk', 0, 0);
}
public static function instance(): self
{
return self::$instance ??= new self();
}
public function isUnassigned(): bool
{
return true;
}
}
class Desk
{
public readonly Member $member;
public function __construct(public readonly string $code, ?Member $member)
{
$this->member = $member ?? UnassignedMember::instance();
}
}
function deskLabel(Desk $desk): string
{
return "{$desk->code}: {$desk->member->name}";
}
function monthlyCharge(Desk $desk, float $baseRate): float
{
return $baseRate * (100 - $desk->member->discountPercent) / 100;
}
function lockersToPrepare(array $desks): int
{
$total = 0;
foreach ($desks as $desk) {
$total += $desk->member->lockers;
}
return $total;
}
function freeDeskCount(array $desks): int
{
return count(array_filter($desks, fn(Desk $d) => $d->member->isUnassigned()));
}
$desks = [
new Desk('A1', new Member('Priya Nair', 15, 2)),
new Desk('A2', null),
];
foreach ($desks as $desk) {
echo deskLabel($desk), ' ', monthlyCharge($desk, 320), PHP_EOL;
}
echo lockersToPrepare($desks), ' ', freeDeskCount($desks), PHP_EOL;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.membercannot 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.memberbecomes 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.freezeand 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.
Write characterization tests for
deskLabel,monthlyCharge,lockersToPrepareandfreeDeskCount, covering a desk with a member and a desk with null. Run them and confirm they pass.Add an
isUnassignedproperty or method toMemberthat returns false. Nothing calls it yet, so the tests still pass.Create
UnassignedMemberas a subclass ofMember. Its constructor passes the defaults the callers currently hard-code ("hot desk", 0, 0), and it overridesisUnassignedto return true. Create one shared, immutable instance.Add a temporary helper
isUnassigned(member)that returns true whenmemberis null or whenmember.isUnassignedis true. Replace everydesk.member === nullcheck with a call to this helper. Run the tests.Change the
Deskconstructor to store the sharedUNASSIGNEDinstance whenever it receives null, and tighten the field type toMember. The helper handles both forms, so the tests stay green.Inline the helper. Since
desk.membercan no longer be null, replace each call withdesk.member.isUnassignedand delete the helper. Run the tests.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.
Keep explicit
isUnassignedchecks only where the caller really needs to distinguish empty desks, such asfreeDeskCount. Review the remaining callers to confirm none still comparememberwith 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.