Temporary Field

Fields only used in specific circumstances.

“An object where a field is only set in certain circumstances.” – Fowler & Beck

Signs of Use (Symptoms)

  • A field is null or undefined most of the time.
  • A field is only populated within one specific method.
  • Scattered if (this.tempValue !== null) checks.

Why it is bad (Consequences)

  • Confusion: Developers expect fields to always be meaningful.
  • Null Checks: Defensive code required everywhere.

Why it happens (Root Cause)

A class was extended to handle a special case, and a field was added “just for that”.

When it might be okay (Exceptions)

  • Rarely. Consider Null Object or separating the responsibility.

Explanation

Problem

You add a tempResult field that is only used during one complex algorithm and is empty otherwise.

The Flaw

The class API is misleading. Readers think tempResult is always there.

Real world analogy

A car with a trailer hitch. If you never use a trailer, the hitch is confusing dead weight.

Refactoring Solution

  • Extract Class: Move the temporary field and method to a separate helper object.
  • Introduce Null Object.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Quick fix
  • Confusing API
  • Comparison

    • Related Antipatterns: Large Class.
    • Related Principles: Violates High Cohesion.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)

    PHP

    Good (The Fix)