Replace Temp with Query

Referenced by patterns
Symptom

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.

Goal

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

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

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.

Tradeoff

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

Relief

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.

Trap

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