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:
- In the Source Editor, select the the statements you want to extract.
- Right-click in the highlighted statements and choose Refactor > Extract Method.
The Extract Method dialog box opens.
- Type the name for your method in the Method Name text field and choose the access type from the drop-down list.
- Select the Declare Static checkbox if you want the new method to be static.
- (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.
- Look at the Method Signature Preview in the dialog box to check that the signature is how you expect.
- (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.
- 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.
- 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:
- Selections cannot have more than one output parameter.
- Selections cannot contain a break or continue statement if the corresponding target is not part of the selection.
- Selections cannot contain a return statement that is not the last statement of the selection.
The selected code is not allowed to return conditionally.
- See Also
- Refactoring: Quick Reference
- Extracting a Superclass
- Extracting an Interface
- Renaming a Field or Method
- Undoing Refactoring Changes
Legal Notices