Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Creating a Method from Existing Statements

As your code evolves, you might find it desirable to break some methods up into multiple methods. You can use the Extract Method command to simplify this process. The Extract Method command does the following:

  • Creates a new method and moves the selected statements to that method.
  • Adds a call to the new method in the location from where the statements were moved.

To extract a method from existing statements:

  1. In the Source Editor, select the statements that you want to be extracted into the new method.
  2. Right-click the selection and choose Refactor | Extract Method.
  3. In the Extract Method dialog box, enter a name for the method and select an access level.
  4. If you want the method to be static, select the Static checkbox.
  5. Click Next.

    If you left the Preview All Changes checkbox clear, the method is immediately extracted.

    If you have selected the Preview All Changes checkbox, the changes to be made to your code are listed in the Refactoring window. After verifying the changes, click Do Refactoring to complete the method extraction.

    If you later find that the refactoring has had some consequences that you would like to reverse, you can choose Refactor | Undo.

  • + Share This
  • 🔖 Save To Your Account