You have an expression that is hard to understand.
Place the result of the expression or its parts in separate variables that are self-explanatory.
The main reason for extracting variables is to make a complex expression more understandable, by dividing it into its intermediate parts.
These could be:
- Condition of the
if()operator or a part of the
?:operator in C-based languages
- A long arithmetic expression without intermediate results
- Long multipart lines
Extracting a variable may be the first step towards performing Extract Method if you see that the extracted expression is used in other places in your code.
- More readable code! Try to give the extracted variables good names that announce the variable's purpose loud and clear. More readability, fewer long-winded comments. Go for names like
- More variables are present in your code. But this is counterbalanced by the ease of reading your code.
How to Refactor
Insert a new line before the relevant expression and declare a new variable there. Assign part of the complex expression to this variable.
Replace that part of the expression with the new variable.
Repeat the process for all complex parts of the expression.