NetBeans Refactoring – Part 2

Greetings my fellow programmers! Now that NetBeans 6.8 is released, I decided that this would be the best time to post part two of my NetBeans refactoring tutorial. I highly recommend reading part one before reading this post. Read it here.

The following Java class will be used to illustrate the refactoring techniques in this post:

public class FruitStand {
 int quantity;
 double pricePerUnit;
 double totalPrice = (pricePerUnit + 12.5) * quantity ;
 String[] merchandise = new String[100];

 public void insertIntoDB(String[] names) {
  for (int i = 0; i < names.length; i++)
   names[i] = names[i].toUpperCase();

  // Rest of method...
  }

 public class Apples {
  int quantity = 500;
  double pricePerUnit = 5.99;
 }
}

Some of the images here are not very clear because of page size limitations. You can click on any image to see it in full size.

Extract Interface:

Extract Interface refactoring allows you to select public non-static methods and move them into a separate interface. This can make your code more readable and maintainable. Suppose you want to extract the insertIntoDB method into an interface:

Note that the class FruitStand now implements NewInterface, and that NewInterface has appeared in the package:

Extract Superclass:

Extract Superclass refactoring works exactly the same way as Extract Interface refactoring. However Extract Superclass moves the methods to a new superclass and extends the refactored class (the one from which the methods were pulled). Repeating the same process we did in Extract Interface:

Move Inner to Outer Level:

Move Inner to Outer Level refactoring converts an inner class to a separate external class declared in its own file. It also gives you the option to declare a field for the current outer class. Here, I am going move the inner class Apples to a separate external class:

You can specify a new name for the class that is being moved and optionally, you can select to declare a field for the current outer class and enter a name for that field:

Note that the inner class Apples has disappeared from class FruitStand, and that a new class Apples has appeared in the package:

Introduce Constant:

Introduce Constant refactoring allows you to change a value used in your code into an individual constant. Assume that the owner of the fruit stand decided to deduct 12.5£ from each unit she sells (her business is not paying well!). So, the value of 12.5 will be declared as an individual constant by first highlighting it then choosing Introduce Constant:

You can also choose the name and the access modifier for the newly created constant:

And voila! The constant is declared and used in the statement where 12.5 was used:

Introduce Method:

Sometimes in your code, you notice that there are certain sections that contain similar blocks of code. Introduce Method refactoring can extracts these code fragments into a separate method that can be called anywhere. This makes the code more readable and easier to maintain. Assume that the fruits in the inventory are submitted into a database, but before doing so, their names must be written in upper case letters (it is stupid, I know!). The for loop inside the insertIntoDB method does that. You find out later that you need to do this operation again somewhere else in the code. Instead of writing it again, you can simply extract it into a separate method. To do this, highlight the code you want to convert to a method and choose Introduce Method:

As in Introduce Constant, you get to choose the method name and its access modifier:

And there you go! The method is declared and called where the piece of code was previously written:

Note that your code selections must meet the following criteria:

  • Selections cannot have more than one output parameter.
  • Selections cannot contain a break or continue statements 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.

Encapsulate Fields:

When developing object-oriented code, it is almost a standard to give the fields (variables) private access, and use public methods to change their values or retrieve them- mutator (setter) and accessor (getter), respectively. Encapsulate Fields refactoring allows the automation of this process; it generates getter and setter methods for the desired fields, enabling the changing of the access modifier for those fields and the accessor methods. To illustrate this, I will encapsulate the quantity and pricePerUnit fields:

You can choose which fields to encapsulate and change the visibility modifiers of the fields and accessors:

After clicking Refactor, you will note that accessors and mutators of the chosen fields were added to your code:

And that is it. Hope you enjoyed this two-part tutorial. If you have any question or comment, do not hesitate to contact me or leave a comment here. See you later with another Significant Insignificane tutorial. Cheers!

Share

NetBeans Refactoring – Part 1

This week I decided to give you, my dear readers, a little rest from my blabbering and go technical a bit. I am going to talk about a very powerful and a personal favorite NetBeans feature: Refactoring.

If you do not know NetBeans, it is a free, cross-platform, open-source Integrated Development Environment (IDE) for software developers and a product of Sun Microsystems. An IDE is a software application that provides extensive facilities to programmers for software development, such as a source code editor, a compiler, an interpreter, build automation tools, and a debugger. For more information about NetBeans’ features, visit the official website.

Refactoring is about changing your source code easily. Imagine moving a class between packages and having to edit the package statements manually at the top of each file, or wanting delete a variable in the code and not knowing if it is referenced somewhere else in your application. Performing these types of operations manually can be time consuming and prone to error. However, with the advanced refactoring capability available in NetBeans, you can do such changes very easily. NetBeans provides many refactoring options on its Refactor menu. I am going illustrate half of them today and the other half in a following post.

EDIT: Part 2 is now available. Click here to read it.

For this post I have created two classes, ImportingClass and MoveClass. View them here and here.

There are some images that are not very clear because of page size limitations. You can click on any image to see it in full size.

Rename:

Rename refactoring allows you to change not only the name of the class but also any constructors, internal usages, and references to the renamed class by other classes. You can also rename the package, which will automatically rename all instances of the package name in your code, including comments. Here, I am going to change the name of the variable value to AddedValue in class ImportingClass:

Automatically, the variable name is also changed in class MoveClass:

Move:

Moving a class from one package to another may seem like an easy task; you just have to copy and paste the contents of the source file into the new directory and then edit the package statement at the top of the file then you are good to go. However, if other classes import or reference that class, then the developer must also search through and modify those files. Here is how you can move MoveClass from the refactoringpackage2 package to refactoringpackage1:

Copy:

Copy refactoring allows you to copy the contents of a class to another package, automatically changing the package statement at the top of the source file.

Safe Delete:

Sometimes when you are reviewing a previously written code, you decide to remove a class member variable that you think is not used, only to find out that it does indeed appear in your code, and then your class does not compile. With Safe Delete refactoring, you can identify each usage of a class, method, or field in code before deleting it. I am going to illustrate it by trying to delete the AddedValue variable from class ImportingClass:

However, the variable was referenced in class MoveClass, so deleting it would cause an error. T=NetBeans alerts you to that, and can even show you where the member you want to delete is referenced if you clicked the “Show Usages…” button:

Change Method Parameters:

Change Method Parameters allows you to safely change everything in a method header- access modifier and arguments- and notifies you if this change is going to affect your source file. Here, I am going to try to delete the parameter x of the display method of class ImportingClass:

Parameter x is used within the method body, and so a warning is displayed:

For the following examples, I created a class called Truck, which inherits fr0m a class called Vehicle. View here.

Pull Up:

When working with classes and superclasses, Pull Up refactoring is very useful. It allows you to move class members and methods from a subclass up into the superclass.

Push Down:

Push Down is the opposite of Pull Up refactoring. It pushes a superclass member down into a subclass.

And that’s it for this time, note that those are only half of the capabilities of NetBeans refactoring. I am going to go through the other half in a following post soon. If you have any question or comment, do not hesitate to contact me.

EDIT: Part 2 is now available. Click here to read it.

Share