47
Replace Temp with Query
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 refactoringfunction bill() {
if (basePrice() > 1000) return basePrice() * 0.95;
return basePrice();
}
function basePrice() { return qty * itemPrice; }Savings
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.
Note
If the temp wraps an expensive calculation called many times, naive replacement may multiply cost — measure or cache before deciding.