Java Refactoring in NetBeans

Exclusive offer: get 50% off this eBook here
NetBeans IDE 7 Cookbook

NetBeans IDE 7 Cookbook — Save 50%

Over 70 highly focused practical recipes to maximize your output with NetBeans

$26.99    $13.50
by Rhawi Dantas | June 2011 | Java Open Source

NetBeans includes a comprehensive set of features for automated refactoring, that will prove very useful to developers. In this article we will create examples that use NetBeans to move, extract, and create classes, methods, and interfaces.

In this article by Rhawi Dantas, author of NetBeans IDE 7 Cookbook, we will cover:

  • Renaming elements
  • Moving elements
  • Extracting a superclass
  • Extracting an interface
  • Encapsulating fields

 

NetBeans IDE 7 Cookbook

NetBeans IDE 7 Cookbook

Over 70 highly focused practical recipes to maximize your output with NetBeans

        Read more about this book      

(For more resources on NetBeans, see here.)

Introduction

Be warned that many of the refactoring techniques presented in this article might break some code. NetBeans, and other IDEs for that matter too, make it easier to revert changes but of course be wary of things going wrong.

With that in mind, let's dig in.

 

Renaming elements

This recipe focuses on how the IDE handles the renaming of all elements of a project, being the project itself, classes, methods, variables, and packages.

How to do it...

Let's create the code to be renamed:

  1. Create a new project, this can be achieved by either clicking File and then New Project or pressing Ctrl+Shift+N.
  2. On New Project window, choose Java on the Categories side, and on the Projects side select Java Application. Then click Next.
  3. Under Name and Location: name the project as RenameElements and click Finish.

With the project created we will need to clear the RenameElements.java class of the main method and insert the following code:

package renameelements;
import java.io.File;
public class RenameElements {
private void printFiles(String string) {
File file = new File(string);
if (file.isFile()) {
System.out.println(file.getPath());
} else if (file.isDirectory()) {
for(String directory : file.list())
printFiles(string + file.separator + directory);
}
if (!file.exists())
System.out.println(string + " does not exist.");
}
}

The next step is to rename the package, so place the cursor on top of the package name, renameelements, and press Ctrl+R.

A Rename dialog pops-up with the package name. Type util under New Name and click on Refactor.

NetBeans IDE 7 Cookbook

Our class contains several variables we can rename:

  1. Place the cursor on the top of the String parameter named string and press Ctrl+R.
  2. Type path and press Enter

Let's rename the other variables:

  1. Rename file into filePath.

To rename methods, perform the steps below:

  1. Place the cursor on the top of the method declaration, printFiles, right-click it then select Refactor and Rename....
  2. On the Rename Method dialog, under New Name enter recursiveFilePrinting and press Refactor.

Then let's rename classes:

  1. To rename a class navigate to the Projects window and press Ctrl+R on the RenameElements.java file.
  2. On the Rename Class dialog enter FileManipulator and press Enter.

And finally renaming an entire project:

  1. Navigate to the Project window, right-click on the project name, RenamingElements, and choose Rename....
  2. Under Project Name enter FileSystem and tick Also Rename Project Folder; after that, click on Rename.

NetBeans IDE 7 Cookbook

How it works...

Renaming a project works a bit differently from renaming a variable, since in this action NetBeans needs to rename the folder where the project is placed. The Ctrl+R shortcut is not enough in itself so NetBeans shows the Rename Project dialog. This emphasizes to the developer that something deeper is happening.

When renaming a project, NetBeans gives the developer the possibility of renaming the folder where the project is contained to the same name of the project. This is a good practice and, more often than not, is followed.

 

Moving elements

NetBeans enables the developer to easily move classes around different projects and packages.

No more breaking compatibility when moving those classes around, since all are seamlessly handled by the IDE.

Getting ready

For this recipe we will need a Java project and a Java class so we can exemplify how moving elements really work.

The exisiting code, created in the previous recipe, is going to be enough. Also you can try doing this with your own code since moving classes are not such a complicated step that can't be undone.

Let's create a project:

  1. Create a new project, which can be achieved either by clicking File and then New Project or pressing Ctrl+Shift+N.
  2. In the New Project window, choose Java on the Categories side and Java Application on the Projects side, then click Next.
  3. Under Name and Location, name the Project as MovingElements and click Finish.
  4. Now right-click on the movingelements package, select New... and Java Class....
  5. On the New Java Class dialog enter the class name as Person.
  6. Leave all the other fields with their default values and click Finish.

How to do it...

  • Place the cursor inside of Person.java and press Ctrl+M.
  • Select a working project from Project field.
  • Select Source Packages in the Location field.
  • Under the To Package field enter: classextraction:
  • NetBeans IDE 7 Cookbook

    How it works...

    When clicking the Refactor button the class is removed from the current project and placed in the project that was selected from the dialog.

    The package in that class is then updated to match.

     

    Extracting a superclass

    Extracting superclasses enables NetBeans to add different levels of hierarchy even after the code is written.

    Usually, requirements changing in the middle of development, and rewriting classes to support inheritance would quite complicated and time-consuming.

    NetBeans enables the developer to create those superclasses in a few clicks and, by understanding how this mechanism works, even creates superclasses that extend other superclasses.

    Getting ready

    We will need to create a Project based on the Getting Ready section of the previous recipe, since it is very similar.

    The only change from the previous recipe is that this recipe's project name will be SuperClassExtraction.

    After project creation:

    1. Right-click on the superclassextraction package, select New... and Java Class....
    2. On the New Java Class dialog enter the class name as DataAnalyzer.
    3. Leave all the other fields with their default values and click Finish.

    Replace the entire content of the DataAnalyzer.java with the following code:

    package superclassextraction;
    import java.util.ArrayList;
    public class DataAnalyzer {
    ArrayList<String> data;
    static final boolean CORRECT = true;
    static final boolean INCORRECT = false;
    private void fetchData() {
    //code
    }
    void saveData() {
    }
    public boolean parseData() {
    return CORRECT;
    }
    public String analyzeData(ArrayList<String> data, int offset) {
    //code
    return "";
    }
    }

    Now let's extract our superclass.

    How to do it...

    1. Right-click inside of the DataAnalyzer.java class, select Refactor and Extract Superclass....
    2. When the Extract Superclass dialog appears, enter Superclass Name as Analyzer.
    3. On Members to Extract, select all members, but leave saveData out.
    4. Under the Make Abstract column select analyzeData() and leave parseData(), saveData(), fetchData() out. Then click Refactor.

    NetBeans IDE 7 Cookbook

    How it works...

    When the Refactor button is pressed, NetBeans copies the marked methods from DataAnalyzer.java and re-creates them in the superclass.

    NetBeans deals intelligently with methods marked as abstract. The abstract methods are moved up in the hierarchy and the implementation is left in the concrete class. In our example analyzeData is moved to the abstract class but marked as abstract; the real implementation is then left in DataAnalyzer.

    NetBeans also supports the moving of fields, in our case the CORRECT and INCORRECT fields.

    The following is the code in DataAnalyzer.java:

    public class DataAnalyzer extends Analyzer {
    public void saveData() {
    //code
    }
    public String analyzeData(ArrayList<String> data, int offset) {
    //code
    return "";
    }
    }

    The following is the code in Analyzer.java:

    public abstract class Analyzer {
    static final boolean CORRECT = true;
    static final boolean INCORRECT = false;
    ArrayList<String> data;
    public Analyzer() {
    }
    public abstract String analyzeData(ArrayList<String> data, int
    offset);
    public void fetchData() {
    //code
    }
    public boolean parseData() {
    //code
    return DataAnalyzer.CORRECT;
    }
    }

    There's more...

    Let's learn how to implement parent class methods.

    Implementing parent class methods

    Let's add a method to the parent class:

    1. Open Analyzer.java and enter the following code:

      public void clearData(){
      data.clear();
      }

    2. Save the file.
    3. Open DataAnalyzer.java, press Alt+Insert and select Override Method....
    4. In the Generate Override Methods dialog select the clearData() option and click Generate.
    5. NetBeans will then override the method and add the implementation to DataAnalyzer.java:

    @Override
    public void clearData() {
    super.clearData();
    }

     

    NetBeans IDE 7 Cookbook Over 70 highly focused practical recipes to maximize your output with NetBeans
    Published: May 2011
    eBook Price: $26.99
    Book Price: $44.99
    See more
    Select your format and quantity:

     

            Read more about this book      

    (For more resources on NetBeans, see here.)

    Extracting an interface

    As with Extracting a superclass, NetBeans also enables the developer to create interfaces out of pre-existing concrete classes.

    As with superclasses, it is also possible to create a more complex hierarchy when extending different interfaces and combining the m together.

    Getting ready

    We will need to create a project based on the Getting Ready section of the previous recipe, since it is very similar.

    The only change from the previous recipe is that this recipe's project name will be InterfaceExtraction.

    1. Now right-click on the interfaceextraction package, select New... and Java Class....
    2. On the New Java Class dialog enter the class Name as DataAnalyzer.
    3. Leave all the other fields with their default values and click Finish.

    Replace the entire content of DataAnalyzer.java with the following code:

    package interfaceextraction;
    import java.util.ArrayList;
    public class DataAnalyzer {
    ArrayList<String> data;
    static final boolean CORRECT = true;
    static final boolean INCORRECT = false;
    private void fetchData() {
    //code
    }
    void saveData() {
    }
    public boolean parseData() {
    return CORRECT;
    }
    public String analyzeData(ArrayList<String> data, int offset) {
    //code
    return "";
    }
    }

    Now let's extract our interface.

    How to do it...

    1. Right-click inside of the DataAnalyzer.java class, select Refactor and Extract Interface....
    2. When the Extract Interface dialog appears, enter Interface Name as IDataAnalyzer.
    3. On Members to Extract select both methods and click Refactor.

    NetBeans IDE 7 Cookbook

    How it works...

    NetBeans copies the method declaration of selected methods contained in our concrete class and creates an interface with them.

    Then our concrete class is marked with the implements keyword.

    The interface is then placed in the same package as our concrete class.

    package interfaceextraction;
    import java.util.ArrayList;
    public interface IDataAnalyzer {
    String analyzeData(ArrayList<String> data, int offset);
    boolean parseData();
    }

    There's more...

    Extracting interface from classes that already have an interface; undoing interface extraction; and understanding the options when refactoring.

    Creating interfaces for classes that already implement interfaces

    Let's create another interface directly from the class that already implements an interface.

    Change the access modifier of fetchData method from default to public:

    public void saveData() {
    //code
    }

    Perform the Extract Interface process one more time:

    1. Right-click inside of the DataAnalyzer.java class, select Refactor and Extract Interface....
    2. When the Extract Interface dialog appears, enter as Interface Name IDatabaseAccess.
    3. On Members to Extract, this time select implements IDataAnalyzer and saveData and click Refactor.

    NetBeans IDE 7 Cookbook

    As seen in the previous screenshot another option is given to the developer, the implements IDataAnalzyer.

    This option will replace the interface that the class is currently implementing with the newly generated one, and then extend that new interface with the original.

    Here is some code to exemplify:

    Our class:

    public class DataAnalyzer implements IDataAnalyzerDB

    Our new interface:

    public interface IDataAnalyzerDB extends IDataAnalyzer

    Undoing interface extraction

    Don't worry, NetBeans is well-prepared for this situation.

    Simply right-click DataAnalyzer.java, and inside of the Refactor sub-menu there is the Undo [Extract Interface] option.

    NetBeans IDE 7 Cookbook

    Refactoring options

    When clicking Preview in the Extracting Interface the developer is presented with the Refactoring Options.

    In this window it is possible to go into great detail over what will get refactored during the above tasks.

    NetBeans IDE 7 Cookbook

    In this dialog we can select any, all or none of the hierarchical options.

    It is possible, for example, not to enable the creation of the interface, even though this would have the consequence of code not compiling, but this gives the developer the chance to make necessary changes to whatever is needed.

     

    Encapsulating fields

    Encapsulation is one of the core principles of object-oriented programming and NetBeans goes to great lengths to simplify the process of generating the necessary code for it.

    Getting ready

    Creating the code to be encapsulated:

    We will need to create a project based on the first Getting Ready section of this article, since it is very similar.

    The only change from the previous recipe is that this recipe's project name will be EncapsulatingFieldsProject.

    We will also need to add a Java class with Person as the class name with entities as the package name.

    Replace the code within Person.java with:

    package entities;
    public class Person {
    long id;
    String firstName;
    String lastName;
    int age;
    String address;
    String email;
    }

    And save the file.

    How to do it...

    With Person.java open in the Java editor:

    1. Right-click inside of Person.java.
    2. Select Refactor and Encapsulate Fields....
    3. On the Encapsulate Fields dialog, in the top right corner click on Select All and then click Refactor.

    NetBeans IDE 7 Cookbook

    How it works...

    NetBeans does a great job when creating all the getters and setters with the default values, even letting the developer select each individual method for each property.

    This gives a good balance of what should be made accessible and how it should be accessible.

    By leaving all of the default options in the field, NetBeans marks all variables as private, adds get/set methods for each variable and documents them.

    Here is a snippet of the generated code for the FirstName property:

    private String firstName;
    /**
    * @return the firstName
    */
    public String getFirstName() {
    return firstName;
    }
    /**
    * @param firstName the firstName to set
    */
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }

    There's more...

    We will better understand the many options provided by the Encapsulate dialog in NetBeans by considering what follows.

    Understanding encapsulate fields options

    The options presented by the Encapsulate Field dialog are very straightforward:

    • Sort By NetBeans will sort the access methods depending on the option selected.
    • Getter/Setter pair organizes the methods by their common field.
    • Getter then Setters organizes the methods with all the getters preceding setters.
    • Method Name organizes methods by their own names.

    NetBeans IDE 7 Cookbook

    Javadoc option enforces the location where the Javadoc for the accessor methods will come from.

    Be it by copying from the fields with the Copy from field option, letting the IDE do the hard work of creating the Javadoc for all of the methods with Create default comments, or simply None.

    NetBeans IDE 7 Cookbook

    Field Visibility enables the developer to choose which Java access modifier should be applied to the variable declaration:

    NetBeans IDE 7 Cookbook

    Accessor Visibility enables the developer to choose which Java access modifier should be applied to the accessor methods (get/set).

    Summary

    In this article we saw how to refactor your code to extract classes, interfaces, encapsulate fields, and other options.


    Further resources on this subject:


    NetBeans IDE 7 Cookbook Over 70 highly focused practical recipes to maximize your output with NetBeans
    Published: May 2011
    eBook Price: $26.99
    Book Price: $44.99
    See more
    Select your format and quantity:

    About the Author :


    Rhawi Dantas

    Rhawi Dantas is a Brazilian Software Engineer, more specifically from Recife, with severeal years of experience in the Java platform. He has mainly focused on Web/Server development and has contributed to projects ranging from mobile/server integration, different customization of IDEs and development of CRMs. He currently works at Paf.com with Java Web development.

    He graduated as Bachelor in Information Systems and at that time he had the opportunity to work as a tutor for the University with Object Oriented Programming subject. Besides fulltime work he is on his way with his Masters in Software Systems at the Tampere University of Technology.

    He is also certified as SCJP, SCWCD, and SCSNI.

    Books From Packt


    NetBeans Platform 6.9 Developer's Guide
    NetBeans Platform 6.9 Developer's Guide

    Java EE 6 Development with NetBeans 7
    Java EE 6 Development with NetBeans 7

    iReport 3.7
    iReport 3.7

    Java EE 6 with GlassFish 3 Application Server
    Java EE 6 with GlassFish 3 Application Server

    BlackBerry Java Application Development
    BlackBerry Java Application Development

    Apache Maven 3 Cookbook
    Apache Maven 3 Cookbook

    jQuery 1.4 Reference Guide
    jQuery 1.4 Reference Guide

    Learning jQuery 1.3
    Learning jQuery 1.3


    Code Download and Errata
    Packt Anytime, Anywhere
    Register Books
    Print Upgrades
    eBook Downloads
    Video Support
    Contact Us
    Awards Voting Nominations Previous Winners
    Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
    Resources
    Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software