Extract function / Extract method

Examine

Identify a section of a function or method which you would like to extract to its own function.

Prepare

Scan the section of code you plan to extract for variables that should become arguments to the method. Do ‘Extract Variable’ on them and move them to before the block of code you want to extract. In a similar way, work out what variables are updated and will need to be returned from the new function. If there are more than one, consider either extracting more than one method, or creating a new type to encapsulate all the updated values in one return value. Even if your language supports multiple return values, it’s wise to consider this, since a function with a single return value is simpler to understand and maintain.

Implement

If that doesn’t work, these are some manual steps:

Clear

Follow up

Consider if the new method has Feature Envy and if it should be moved somewhere else.

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings