Extract Variable / Introduce Variable
Identify an expression that you’d like to extract as a named variable.
Select the expression. Preferably use the IDE’s ‘expand selection’ functionality to make sure it’s a valid expression. Inspect the highlighted code to ensure there are no side effects.
IDE: while you have the expression selected, use ‘introduce variable’ or similar from the refactoring menu.
- Copy the selected expression
- Declare a new variable with a suitable name, before the first place the expression is used. Set the new variable to the selected expression using Paste.
- Replace the original expression with the new variable.
If the same expression appears in several places, replace the others too, testing after every replacement.
Ensure the name of the new variable makes sense in all contexts, Rename if needed.
- You could introduce the variable as a parameter to the enclosing method.
- You could introduce the variable as a field of the enclosing class
- You could slide statement in order to initialize the variable earlier in the code.
- You could extract method on the following section of code that uses the variable, so it will be passed as a parameter to the new method.
Prompted by Code Smells
Relevant Learning Hours
- This refactoring is included Martin Fowler's book "Refactoring", 2nd Edition
Back to All Refactorings