Extracting a Method

See Also

When you extract a method in the IDE you change a selected code fragment into a method. Typically you extract a method when you want to separate a method into smaller, more meaningful methods. Creating smaller fragments can increase the reusability of your code as you can separate the parts of your code that may need to be updated more often. By giving your new method a meaningful name, you can increase the comprehensibility of your code.

When you extract a method in the IDE, you replace statements in a class with a call to a method. Before statements are replaced, the IDE opens the Extract Method dialog box where you specify the parameters and modifiers for the method. The IDE searches your open projects for occurrences of the statements you specified and replaces the occurrences with the method call.

To extract a method:

  1. In the Source Editor, select the the statements you want to extract.
  2. Right-click in the highlighted statements and choose Refactor > Extract Method.

    The Extract Method dialog box opens.

  3. Type the name for your method in the Method Name text field and choose the access type from the drop-down list.
  4. Select the Declare Static checkbox if you want the new method to be static.
  5. (Optional) Change the order of the parameters by selecting a parameter and using the Move Up and Move Down buttons.

    The parameters listed in the dialog box are those you initially selected.

  6. (Optional) Clear the checkbox if you do not want to preview the changes before they are made. If Preview All Changes is not selected, the IDE applies the changes automatically and skips the remaining steps.
  7. Click Next. If Preview All Changes is selected, the Refactoring window opens and displays all occurences that will be affected by the change. Review the list and clear the checkbox of any code that you do not want changed.
  8. Click Do Refactoring in the Refactoring window to apply the changes to the selected files.

Troubleshooting

If you encounter an error message when extracting a method, check to see that the statements you selected meet the following criteria:

See Also
Refactoring: Quick Reference
Extracting a Superclass
Extracting an Interface
Renaming a Field or Method
Undoing Refactoring Changes

Legal Notices