Skip to content

Replace Temp with Query

Take a local variable that is assigned the result of a calculation and then only read, and replace it with a function (a “query”) that performs the calculation. Every place that used the temp now calls the query.

This cures temps that pin logic in place. A temporary variable couples a calculation to one function: you cannot reuse the result elsewhere, and you cannot Extract Function around code that depends on it without dragging the temp along as a parameter. Turning the temp into a query frees the calculation. It is most valuable as a preparation step — once the value is a method, larger extractions fall out cleanly.

basePrice is a temp computed once and read twice. Promote it to a query method on the order.

// Before
class Order {
constructor(private quantity: number, private itemPrice: number) {}
finalPrice(): number {
const basePrice = this.quantity * this.itemPrice;
const discount = Math.max(this.quantity - 100, 0) * this.itemPrice * 0.1;
return basePrice - discount;
}
}
// After
class Order {
constructor(private quantity: number, private itemPrice: number) {}
private basePrice(): number {
return this.quantity * this.itemPrice;
}
private discount(): number {
return Math.max(this.quantity - 100, 0) * this.itemPrice * 0.1;
}
finalPrice(): number {
return this.basePrice() - this.discount();
}
}
  1. Check the temp is assigned exactly once and is never mutated after assignment. If it is reassigned, split it first so each value is determined in one place.
  2. Confirm the right-hand-side calculation has no side effects.
  3. Extract the calculation into a query function (a method when the data lives on an object).
  4. Replace each read of the temp with a call to the query.
  5. Run your tests after each replacement.
  6. Remove the now-unused temp declaration.

Use it when a temp blocks an Extract Function you want to do, when the same calculation would be useful from more than one method, or simply to shrink a long method’s local state. The main trade-off is repeated computation: a query may recalculate on every call. For typical business logic this is negligible, and the clarity is worth it; for a genuinely hot path, measure before deciding.

The opposite direction is caching the value back into a local when profiling proves the query is a real bottleneck — but reach for that only with evidence.

What does Replace Temp with Query replace a local variable with?
What condition should the temp meet before applying this refactoring?
Why is this refactoring often used as a preparation step?