Techniquecore
Replace temp with query
Also called replace variable with query.
Replace a local variable that holds a computed value with a function that computes it, so that other functions can ask for the value and the long function gets easier to split.
- Family
- refactoring
- Intent
- Turn a computed local variable into a query function that any method of the class can call.
Purpose
A local variable gives a computed value a name, which helps the reader. It also has a cost: the value exists only inside one function. Another method that needs the same value must compute it again, and a long function full of such variables is hard to split, because each part that is extracted needs the variables as parameters.
Replace temp with query moves the computation into a function, often a getter of the class, and replaces the variable with calls of that function. The catalogue card shows a temp basePrice, computed as this._quantity * this._itemPrice, becoming a getter basePrice that the code then calls.1 Now the value has a name that every method of the class can use, and an Extract Function on the code that used the temp needs no parameter for it.2
The book notes that the refactoring fits a class well, where the query has the fields of the object as its context, and that it is for variables that are computed once and then only read.2 The first edition has it among the refactorings for composing methods.3
Steps
- Run the tests and see them pass.
- Check that the variable is fully computed before it is used, and that the code that computes it gives the same value each time it runs.2
- If the variable is not read-only, make it so, and test.
- Extract the right side of the assignment into a function. If the variable and the function cannot have the same name, give the function a temporary name.
- Check that the function has no side effects. If it has, separate the query from the modifier first.2
- Test.
- Use Inline Variable to replace the variable with calls of the function, and test.
Example
A rental computes a subtotal and a fee in local variables. A second method, the receipt, needs the same values and computes them again. After the refactoring, both use the queries.
import assert from "node:assert/strict";
// Before: temps inside one method; the receipt repeats the rules.
class RentalBefore {
constructor(days, dailyRate) { this.days = days; this.dailyRate = dailyRate; }
total() {
const subtotal = this.days * this.dailyRate;
const fee = subtotal > 500 ? 0 : 25;
return subtotal + fee;
}
receipt() {
const subtotal = this.days * this.dailyRate; // the rule again
const fee = subtotal > 500 ? 0 : 25;
return `${subtotal} + ${fee}`;
}
}
// After: queries that every method can ask.
class Rental {
constructor(days, dailyRate) { this.days = days; this.dailyRate = dailyRate; }
get subtotal() { return this.days * this.dailyRate; }
get fee() { return this.subtotal > 500 ? 0 : 25; }
total() { return this.subtotal + this.fee; }
receipt() { return `${this.subtotal} + ${this.fee}`; }
}
for (const [d, r] of [[2, 100], [6, 100], [5, 100]]) {
const a = new RentalBefore(d, r);
const b = new Rental(d, r);
assert.equal(b.total(), a.total());
assert.equal(b.receipt(), a.receipt());
}
assert.equal(new Rental(6, 100).receipt(), "600 + 0");
console.log("replace temp with query: tests pass");
replace temp with query: tests pass
The rule for the fee now has one home. A change to it, such as a different threshold, changes total and receipt together.
| Language | What the example shows |
|---|---|
| JavaScript | getters that replace the temps, as above |
| Python | @property queries, and functools.cached_property when the value is costly and the object does not change |
| Go | methods as queries on a struct |
from functools import cached_property
class Rental:
def __init__(self, days, daily_rate):
self.days = days
self.daily_rate = daily_rate
@property
def subtotal(self): # a query, computed when it is asked
return self.days * self.daily_rate
@property
def fee(self):
return 0 if self.subtotal > 500 else 25
def total(self):
return self.subtotal + self.fee
r = Rental(2, 100)
assert (r.subtotal, r.fee, r.total()) == (200, 25, 225)
r.days = 6 # a query follows the change; a temp taken before would not
assert r.total() == 600
class Quote:
"""An object that does not change, so a costly value can be cached."""
calls = 0
def __init__(self, items):
self._items = tuple(items)
@cached_property
def subtotal(self):
Quote.calls += 1
return sum(self._items)
q = Quote([120, 80])
assert q.subtotal == q.subtotal == 200
assert Quote.calls == 1 # computed once
print("replace temp with query: tests pass")
replace temp with query: tests pass
package main
import "fmt"
type Rental struct {
Days int
DailyRate int
}
// Methods are the queries. Each method of the type can ask them.
func (r Rental) Subtotal() int { return r.Days * r.DailyRate }
func (r Rental) Fee() int {
if r.Subtotal() > 500 {
return 0
}
return 25
}
func (r Rental) Total() int { return r.Subtotal() + r.Fee() }
func (r Rental) Receipt() string { return fmt.Sprintf("%d + %d", r.Subtotal(), r.Fee()) }
func main() {
for _, r := range []Rental{{2, 100}, {6, 100}} {
fmt.Println(r.Receipt(), "=", r.Total())
}
if (Rental{5, 100}).Total() != 525 {
panic("unexpected total")
}
fmt.Println("replace temp with query: tests pass")
}
200 + 25 = 225
600 + 0 = 600
replace temp with query: tests pass
When to use
- Another function needs the same value. A query removes the repeated computation.
- Before an Extract Function. A temp that the extracted code uses would become a parameter. A query does not.2
- In a Long Function. Temps are one of the things that hold a long function together. Replacing them is often the first step of splitting it.
Pitfalls
A snapshot. Some variables exist to keep a value from a moment in time, before a change. A query computes the value when it is called, so it gives the value after the change. Keep the variable in that case.2
A query with side effects. If the computation changes state, calling it several times changes the state several times. Separate the query from the modifier before you replace the temp.
Cost. A query that is called several times computes the value several times. For a cheap expression, this does not matter. For a costly one, cache the result in the object if the data does not change, or keep the variable.
A variable that is assigned more than once. A temp that is set, then changed in a loop, is an accumulator, not a computed value. Split the variable first, or leave it.
Tools that do it
This refactoring is two tool steps: an extract of the expression into a function or a method, and an inline of the variable. The tools of the other pages of this area do the extraction. In IntelliJ IDEA, Inline Variable "replaces redundant variable usage with its initializer", so it is applied after the extraction, when the initializer is a call of the query.4
References
- Martin Fowler, Catalog of Refactorings, Replace Temp with Query, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 7, Encapsulation, Replace Temp with Query, motivation and mechanics
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 6, Composing Methods, Replace Temp with Query
- IntelliJ IDEA documentation, Inline, Inline Variable
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag SYBXKD Edit this page History Report an error Markdown