The purpose of the extract method refactoring is to turn a section of code into a new method. The method should be given a name that accurately describes the purpose of the extracted section of code. Extracting methods allows the code to be self documenting and also allows the code to be reused elsewhere thereby reducing duplication.

Example

Here is the original code, unmodified.

Step 1: Create a new and appropriately named empty private method. If the method does not reference any instance variables, then make the method static as well. Verify that none of the temporary variables in the extracted code will be used again in the original method.

Step 2: Copy the extracted code from the original method into the new method.

Step 3: Create method parameters for any local variables in the new method that need to be passed in from the original method.

Step 4: Assign the return value of the method (if it has one). Comment out the extracted code. Re-run your test suite.

Step 5: Deleted the commented code and clean up formatting as needed. Variable and parameter naming can be cleaned up was well. Re-run the test suite again.