Null Check Hell

Excessive null checks throughout the code.

“I call it my billion-dollar mistake… the invention of the null reference.” – Tony Hoare

Signs of Use (Symptoms)

  • if (x !== null && x !== undefined) everywhere.
  • Chains of null checks: if (a && a.b && a.b.c).
  • Optional chaining overuse: a?.b?.c?.d?.e.

Why it is bad (Consequences)

  • Clutter: Defensive code everywhere.
  • Bugs: Miss one check, get null crash.

Why it happens (Root Cause)

APIs return null for “not found” or uninitialized values.

When it might be okay (Exceptions)

  • External data at boundaries (but consider transforming early).

Explanation

Problem

Every function receives nullable inputs and must guard against them.

The Flaw

Null spreads like a virus. Design to avoid it.

Real world analogy

A game of hot potato where everyone checks if the potato has been replaced with a bomb.

Refactoring Solution

  • Null Object Pattern: Return a no-op object instead of null.
  • Option/Maybe type: Use Option<T> to encode nullability.
  • Fail Fast at boundary: Validate at entry, then assume non-null.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Safety at each step
  • Noise
  • Easy to miss a check
  • Comparison

    • Related Antipatterns: None directly.
    • Related Principles: Fail Fast.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)