Replace Temp with Query
Move the entire expression to a method and replace references to the temp with calls to the method.
“You are using a temporary variable to hold the result of an expression. Extract the expression into a method.”
Turn variables into functions.
graph LR
A[Variable] -->|Refactoring| B[Function Call]
When to apply (Smells)
- Long Method: Temps often force methods to be long because they are only visible locally.
- Duplicate Logic: The calculation is needed elsewhere.
Motivation
- Reusability: Logic in a method is reusable; logic in a temp is not.
- Cleaner scope: Removes local variables, making Extract Method easier.
Mechanics (Steps)
- Extract the expression into a new method (it should be side-effect free / pure).
- Replace references to the temp with calls to the new method.
- Remove the temp.
Explanation
Problem
You place the result of an expression in a local variable for later use.
Solution
Move the entire expression to a separate method and return the result from it. Query the method instead of using a variable.
Real world analogy
Instead of calculating the bill, writing it on a napkin (temp), and carrying the napkin around, you just ask the waiter (query) whenever you need to know the total.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Related: Extract Method.
Code example
Typescript
Before
After
PHP
Before
After