Skip to content

Temporary Field: State That Only Lives During One Method Call

How to spot object fields that hold meaningful values only while one operation runs, why they cause bugs, and how to refactor them away.

6 min readCode smellMisused abstractions

A temporary field is an instance field that only holds a meaningful value while one particular method runs. Before that call it is null, zero or stale. After the call it still holds leftovers from the last run. The rest of the class ignores it. The field usually starts out as a shortcut. A long algorithm needs a handful of intermediate values, passing them between helper methods feels clumsy, so they get stored on this. The class now looks stateful when it isn't. Readers have to work out when each field is valid, and every helper quietly depends on being called in the right order. In an interview, this smell is a good test of whether you can tell an object's real state from the scratch work of a single computation.

Signs

How to spot it in a review.

  • Fields that are reset at the start of one public method and never read anywhere else.
  • Helpers that throw or misbehave if called outside a specific parent method, such as a check like if (this.zone === null) throw.
  • A comment like "only valid during X()" next to a group of fields.
  • Nullable fields whose null case means "the operation hasn't started yet" rather than a real domain state.
  • Values left over from the previous call that could leak into the next one if a reset line is forgotten.
  • An otherwise stateless service that becomes unsafe to share between threads or reentrant calls.

What it looks like

A typical case, in three languages.

interface Parcel {
  lengthCm: number;
  widthCm: number;
  heightCm: number;
  weightKg: number;
}

interface QuoteRequest {
  originPostcode: string;
  destPostcode: string;
  parcels: Parcel[];
  express: boolean;
}

class ShipmentQuoter {
  // Only meaningful while quote() is running
  private zone: number | null = null;
  private billableKg = 0;
  private oversizeCount = 0;

  constructor(private readonly ratePerKgByZone: Record<number, number>) {}

  quote(req: QuoteRequest): number {
    this.zone = this.resolveZone(req.originPostcode, req.destPostcode);
    this.billableKg = 0;
    this.oversizeCount = 0;
    for (const p of req.parcels) {
      this.accumulate(p);
    }
    return this.price(req.express);
  }

  private resolveZone(from: string, to: string): number {
    if (from.slice(0, 2) === to.slice(0, 2)) return 1;
    if (from[0] === to[0]) return 2;
    return 3;
  }

  private accumulate(p: Parcel): void {
    const volumetricKg = (p.lengthCm * p.widthCm * p.heightCm) / 5000;
    this.billableKg += Math.max(p.weightKg, volumetricKg);
    if (Math.max(p.lengthCm, p.widthCm, p.heightCm) > 120) {
      this.oversizeCount++;
    }
  }

  private price(express: boolean): number {
    if (this.zone === null) {
      throw new Error("price() called outside quote()");
    }
    const base = this.billableKg * this.ratePerKgByZone[this.zone];
    const surcharge = this.oversizeCount * 18.5;
    const total = (base + surcharge) * (express ? 1.4 : 1);
    return Math.floor(total * 100 + 0.5) / 100;
  }
}

const quoter = new ShipmentQuoter({ 1: 2.1, 2: 3.4, 3: 5.9 });
console.log(
  quoter.quote({
    originPostcode: "LS12",
    destPostcode: "LS27",
    parcels: [{ lengthCm: 60, widthCm: 40, heightCm: 40, weightKg: 9 }],
    express: false,
  })
);

Tidewater Couriers' ShipmentQuoter is configured once with zone rates and is meant to be shared. But zone, billableKg and oversizeCount exist only for the duration of quote(). The guard in price() exists only because the field can be null between calls. Drop one reset line and the next quote silently inherits the previous customer's weight. The fix is to move this scratch state into a short-lived calculation object, or into locals passed as parameters, so the quoter keeps only its rates.

Why it happens

How code ends up like this.

  • A long method was split into helpers, and storing intermediate values on the object felt easier than passing them as arguments.
  • The class started as a script-like procedure and was wrapped in a class without separating configuration from per-call working data.
  • An optional branch of the algorithm needs extra data, so a nullable field was added that is only set when that branch runs.
  • Developers copied a pattern from frameworks where per-request objects are common, but applied it to a long-lived singleton service.

Treatment

The refactorings that cure it, and when to choose each.

Payoff

What you get once it's gone.

  • The long-lived object keeps only its real state, so it is safe to share across requests, threads and reentrant calls.
  • No leftover values from a previous call can leak into the next one.
  • Helpers no longer depend on hidden call order and can be tested on their own.
  • Null guards that exist only to detect "called at the wrong time" disappear.

When to leave it

Sometimes it's not worth fixing.

  • The object is itself created per operation and thrown away afterwards, such as a parser or a command object. Its fields then are its lifetime state, not temporary ones.
  • A field is a deliberate memoisation cache with clear invalidation rules, and the cost of recomputing is measurably significant.
  • Framework lifecycles force the pattern, for example a test fixture populated in a setup hook and read by every test method.

Common questions

Short answers to the usual doubts.

How is a temporary field different from lazy initialisation?

A lazily initialised field is null until first use, but once set it stays valid for the rest of the object's life and means the same thing on every read. A temporary field is valid only inside one operation and becomes meaningless, or misleading, once that operation returns.

Isn't passing five values between helpers worse than storing them on the object?

If you need that many, the values belong together. Group them into a per-call object, with a command or a parameter object, rather than pinning them to a long-lived service. You keep the convenience of shared state while scoping it to exactly one run.

How would I explain this smell quickly in an interview?

Say that the class mixes two lifetimes: configuration that lives as long as the object, and scratch data that lives for one method call. Point to the reset lines and null guards as evidence, then propose moving the scratch data into a method object or into parameters. Mention thread safety and stale state as the concrete risks.

Does this smell matter in single-threaded languages like JavaScript?

Yes. Even without threads, an async version of the method can interleave two calls on the same instance, and a forgotten reset still leaks state between sequential calls. The design problem of unclear validity stays the same.

Next guide4 of 4 · Smells: misused abstractionsFlag ArgumentsRead the next one