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,
})
);import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Parcel:
length_cm: float
width_cm: float
height_cm: float
weight_kg: float
@dataclass(frozen=True)
class QuoteRequest:
origin_postcode: str
dest_postcode: str
parcels: list[Parcel]
express: bool
class ShipmentQuoter:
def __init__(self, rate_per_kg_by_zone: dict[int, float]) -> None:
self._rates = rate_per_kg_by_zone
# Only meaningful while quote() is running
self._zone: int | None = None
self._billable_kg = 0.0
self._oversize_count = 0
def quote(self, req: QuoteRequest) -> float:
self._zone = self._resolve_zone(req.origin_postcode, req.dest_postcode)
self._billable_kg = 0.0
self._oversize_count = 0
for p in req.parcels:
self._accumulate(p)
return self._price(req.express)
def _resolve_zone(self, origin: str, dest: str) -> int:
if origin[:2] == dest[:2]:
return 1
if origin[0] == dest[0]:
return 2
return 3
def _accumulate(self, p: Parcel) -> None:
volumetric_kg = (p.length_cm * p.width_cm * p.height_cm) / 5000
self._billable_kg += max(p.weight_kg, volumetric_kg)
if max(p.length_cm, p.width_cm, p.height_cm) > 120:
self._oversize_count += 1
def _price(self, express: bool) -> float:
if self._zone is None:
raise RuntimeError("_price() called outside quote()")
base = self._billable_kg * self._rates[self._zone]
surcharge = self._oversize_count * 18.5
total = (base + surcharge) * (1.4 if express else 1)
return math.floor(total * 100 + 0.5) / 100
quoter = ShipmentQuoter({1: 2.1, 2: 3.4, 3: 5.9})
print(
quoter.quote(
QuoteRequest("LS12", "LS27", [Parcel(60, 40, 40, 9)], express=False)
)
)<?php
final class Parcel
{
public function __construct(
public readonly float $lengthCm,
public readonly float $widthCm,
public readonly float $heightCm,
public readonly float $weightKg,
) {}
}
final class QuoteRequest
{
/** @param Parcel[] $parcels */
public function __construct(
public readonly string $originPostcode,
public readonly string $destPostcode,
public readonly array $parcels,
public readonly bool $express,
) {}
}
class ShipmentQuoter
{
// Only meaningful while quote() is running
private ?int $zone = null;
private float $billableKg = 0.0;
private int $oversizeCount = 0;
/** @param array<int, float> $ratePerKgByZone */
public function __construct(private readonly array $ratePerKgByZone) {}
public function quote(QuoteRequest $req): float
{
$this->zone = $this->resolveZone($req->originPostcode, $req->destPostcode);
$this->billableKg = 0.0;
$this->oversizeCount = 0;
foreach ($req->parcels as $p) {
$this->accumulate($p);
}
return $this->price($req->express);
}
private function resolveZone(string $from, string $to): int
{
if (substr($from, 0, 2) === substr($to, 0, 2)) {
return 1;
}
if ($from[0] === $to[0]) {
return 2;
}
return 3;
}
private function accumulate(Parcel $p): void
{
$volumetricKg = ($p->lengthCm * $p->widthCm * $p->heightCm) / 5000;
$this->billableKg += max($p->weightKg, $volumetricKg);
if (max($p->lengthCm, $p->widthCm, $p->heightCm) > 120) {
$this->oversizeCount++;
}
}
private function price(bool $express): float
{
if ($this->zone === null) {
throw new LogicException('price() called outside quote()');
}
$base = $this->billableKg * $this->ratePerKgByZone[$this->zone];
$surcharge = $this->oversizeCount * 18.5;
$total = ($base + $surcharge) * ($express ? 1.4 : 1);
return floor($total * 100 + 0.5) / 100;
}
}
$quoter = new ShipmentQuoter([1 => 2.1, 2 => 3.4, 3 => 5.9]);
echo $quoter->quote(new QuoteRequest('LS12', 'LS27', [new Parcel(60, 40, 40, 9)], false)), PHP_EOL;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.
- Replace Function with Command: Turn a Long Function into an Object
The operation is big enough that its helpers genuinely share several values. Create a
QuoteCalculationbuilt per call; the temporary fields become its normal, always-valid fields. - Extract Class: Split a Class That Does Two Jobs
The temporary fields form a cohesive group, such as a running total plus counters. Move them and the methods that touch them into a small accumulator class created inside the operation.
- Change Function Declaration: Fix a Signature Without Breaking Callers
Only one or two values are involved. Pass them as parameters and return results instead of writing to
this, so the helpers become pure functions. - Replace Temp with Query: Turn Local Variables into Methods
A temporary field caches something cheaply derivable from the input, like the zone. Compute it on demand from the request instead of storing it.
- Introduce Special Case: Replace Repeated Null Checks With an Object
A field is null whenever an optional branch didn't run, and every reader checks for null. Replace the null with a special-case object that supplies neutral behaviour.
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.