Replace Temp with Query

Referenced by patterns
Compare
Symptom
Human

A local variable assigned once from a computation, then referenced one or more times within the same function — `const basePrice = qty * itemPrice;` used multiple times in the body.

Agent

The agent finds a local variable assigned once from a computation and referenced multiple times; the temp's existence couples the rest of the function to the computation's locality.

Goal
Human

A local variable assigned once from a computation becomes a function that returns that computation on demand.

Agent

Computations become named queries the agent can reference by name from anywhere; functions decompose without dragging the temp's lifetime.

Before the refactoring

function bill() {
const basePrice = qty * itemPrice;
if (basePrice > 1000) return basePrice * 0.95;
return basePrice;
}

After the refactoring

function bill() {
if (basePrice() > 1000) return basePrice() * 0.95;
return basePrice();
}
function basePrice() { return qty * itemPrice; }
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure
Human

The temp's lifetime constrains how the surrounding function can be split; Extract Function must drag the temp along; the named computation is locked inside one function.

Agent

The agent extracting parts of the function must thread the temp through every extracted helper; the named computation can't be reused outside the function.

Tradeoff
Human

If the temp wraps an expensive calculation called many times, naive replacement may multiply cost — measure or cache before deciding.

Agent

If the temp wraps an expensive calculation called many times, naive replacement multiplies cost; the agent verifying performance must measure or cache before substituting.

Relief
Human

Extract Function becomes easier (the query has a name and stable scope); the temp's lifetime no longer constrains how the surrounding function is split.

Agent

The value is recomputed from its source at every read; the agent does not track a temp's binding across reads to predict staleness, and the query is callable from any site without the binding's scope constraint.

Trap
Human

Replacing every temp with a query — including ones wrapping an expensive computation referenced many times — multiplies runtime cost without any structural gain.

Agent

Replacing temps that wrap expensive computations called many times multiplies runtime cost the agent's local tests may not catch.