Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required. Paperback excluded.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Java Refactoring in NetBeans

Save for later
  • 7 min read
  • 08 Jun 2011

article-image

 

NetBeans IDE 7 Cookbook


java-refactoring-netbeans-img-0

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

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.

java-refactoring-netbeans-img-1


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.

java-refactoring-netbeans-img-2


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.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime

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:

java-refactoring-netbeans-img-3


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.

java-refactoring-netbeans-img-4


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();
 }