Refactoring techniqueComposing Methods
Inline Temp
Replace a temporary variable that holds a simple expression with the expression itself when the name adds nothing.
- Also known as
- Inline Variable
Problem
A local variable is assigned once from a simple expression and used once or twice. The name repeats what the expression already says, or the variable blocks another refactoring such as Extract Method.
Solution
Replace every reference to the variable with its expression, then delete the declaration.
Before
function shouldThrottle(client: ApiClient, window: RateWindow): boolean {
const requestCount = window.countFor(client.id);
const limit = client.plan.requestsPerMinute;
const over = requestCount > limit;
return over;
}After
function shouldThrottle(client: ApiClient, window: RateWindow): boolean {
return window.countFor(client.id) > client.plan.requestsPerMinute;
}Why
- Less to read when the expression is already self-describing.
- Removes locals that stand in the way of extracting or moving code.
- Fewer names to keep in sync during later edits.
Steps
- Confirm the variable is assigned exactly once. Mark it
constand compile to prove it. - Confirm the right-hand side has no side effects and returns the same value each time it is read in this scope.
- Replace the first reference with the expression. Run the tests.
- Replace the remaining references, then delete the declaration. Run the tests.
Watch out
- Don't inline when the expression is expensive (a query, a network call, a large loop) and the variable is read several times. You would repeat the work.
- Don't inline when the value can change between reads, for example
Date.now()or a mutable field another call updates. - Don't inline when the name explains something the expression does not. That variable is doing the job of Extract Variable, the inverse technique.
- If the expression is long and used in several functions, Replace Temp with Query is a better destination.
Related
- Helps with Long Method by clearing the way for extraction.
- Inverse: Extract Variable.
- Inline Method is the function-level counterpart.
Agent checklist
- The variable had a single assignment.
- The expression is pure and cheap, or is read only once.
- No reader loses information that the variable name carried.
- Tests pass.
Treats these smells
See also
- Extract VariableName a hard-to-read expression or sub-expression by assigning it to a well-named local variable.
- Replace Temp with QueryMove the expression behind a temporary variable into its own method so every method in the class can ask for the value.
- Inline MethodReplace calls to a function whose body is as clear as its name with the body itself, then delete the function.
Original writing and examples. Topic coverage follows Refactoring.Guru, which explains this topic with its own illustrations.