Extract Variable
Put the result of an expression, or parts of it, into a temporary variable with a named identifier.
“Expressions can become very complex and hard to read. Sub-expressions can be extracted into temporary variables with descriptive names.”
Explain the “what” of a complex expression.
graph LR
A[Complex Expression] -->|Refactoring| B[Named Variable]
When to apply (Smells)
- Complex Conditionals:
if (platform.toUpperCase().indexOf("MAC") > -1 && browser.toUpperCase().indexOf("IE") > -1 && ...) - Magic Expressions: Math without context.
Motivation
- Readability: Splits a complex expression into readable parts.
- Debugging: Easier to inspect values in the debugger.
Mechanics (Steps)
- Create a temporary variable.
- Assign the expression to the variable.
- Replace the expression with the variable.
Explanation
Problem
You have an expression that is hard to understand.
if ((platform.toUpperCase().indexOf("MAC") > -1) && (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0 )
Solution
Extract parts into readable variables.
const isMacOs = platform.toUpperCase().indexOf("MAC") > -1;
const isIE = browser.toUpperCase().indexOf("IE") > -1;
if (isMacOs && isIE && ...)
Real world analogy
Instead of saying “The thing that has 4 legs and barks”, you define a name “Dog” and use that.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Inline Temp.
Code example
Typescript
Before
After
PHP
Before
After