Extract Variable / Introduce Variable

Examine

Identify an expression that you’d like to extract as a named variable.

Prepare

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.

Implement

IDE: while you have the expression selected, use ‘introduce variable’ or similar from the refactoring menu.

By hand:

If the same expression appears in several places, replace the others too, testing after every replacement.

Clear

Ensure the name of the new variable makes sense in all contexts, Rename if needed.

Follow up

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings