Split Temporary Variable
Split a variable that serves two different purposes into two variables.
“You have a temporary variable assigned to more than once, but is not a loop variable nor a collecting temporary variable.”
One variable should have one responsibility.
graph LR
A[Reused Temp] -->|Refactoring| B[Two Distinct Temps]
When to apply (Smells)
- Confusion: A variable named
tempholds a height, then later holds a width. - Assignment: Variable is assigned to multiple times with completely different values.
Motivation
- Readability: Each variable should explain its specific purpose.
- Maintenance: Easier to verify and debug.
Mechanics (Steps)
- Change the name of the variable at the first assignment.
- If the variable is
const(or immutable), good. - Change references up to the second assignment.
- Repeat for subsequent assignments.
Explanation
Problem
You have a temporary variable that is assigned to more than once.
Solution
Use a different temporary variable for each assignment.
Real world analogy
Using the same labeled jar for “Sugar” and then later for “Salt”. It’s confusing. Use two jars.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Related: Remove Assignments to Parameters.
Code example
Typescript
Before
After
PHP
Before
After