Channels ▼
RSS

Refactoring with Eclipse


October, 2004: Refactoring with Eclipse

There's no excuse not to refactor anymore

Hugo is a consulting software engineer specializing in web services and n-tier business systems. He can be contacted at trochphauburn.edu.


Refactoring is the process of improving code without changing its functionality. Martin Fowler introduced this concept and refactoring patterns in his book Refactoring: Improving the Design of Existing Code (Addison-Wesley, 1999; ISBN 0201485672). The issue with refactoring is that it involves changing code and these changes may have consequences somewhere else. For example, suppose you implement Fowler's "Introduce Parameter Object" refactoring. In this case, you take the parameters of the signature of a method and create an object that holds those parameters and then just pass that object to the method. Figure 1 shows an example of how to do this refactoring for the method setEngine() of the class Car.

This refactoring simplifies setEngine() and makes it more readable. Not only that, but to add more parameters to setEngine() you just add more member variables to Engine (like make or power). You don't have to change the signature of the method setEngine() in Car. The problem now is that you have to track down all the places in the code that use setEngine() and make the appropriate changes. Here is where the refactoring features of Eclipse can help.

Eclipse provides a collection of refactoring features. For example, if you use Eclipse to do the refactoring of setEngine() in Car, Eclipse shows you automatically all the places in your code that use setEngine() and even tries to do the changes for you. Eclipse provides the necessary tool support to make refactoring quicker and more efficient. Another important feature to support refactoring is automated testing, but I will not go into the testing features of Eclipse.

In this article, I explain the refactoring features of Eclipse, give examples of how to use some of these features, and link the refactoring features to some refactoring patterns. I grouped the refactoring features just as they are grouped in Eclipse. The first section presents the Changing Names features. In the second section, I talk about the Generalization features. The third section goes in the Organizing Methods and Data features. In the last section, I present a few supporting features and final thoughts. Figure 2 shows the menu for the refactoring features of Eclipse.

Changing Names

The Eclipse refactoring feature Rename lets you change the name of a class. Eclipse automatically changes the name of that class in all the classes that are using it. The Move feature lets you move a class from one package to another. Eclipse automatically makes the necessary changes in all the classes using the class you are moving. The Change Method Signature lets you change the signature of a method. Eclipse notifies you about all the places in the code where you are using this method and it gives you an opportunity to make the appropriate changes. The Convert Anonymous Class to Nested class feature converts a selected anonymous class to a member class, while Move Member Type to New File converts a member class to a new Java class and updates the references accordingly.

For instance, to understand how the Change Method Signature feature works, you first select a method by highlighting a whole method in the source editor. Then you select from the Refactor menu the Change Method Signature menu item. A dialog like Figure 3 pops up, which lets you add, edit, and remove parameters. If you add a parameter, you will have the possibility to specify the default value for that parameter. Eclipse places that default value in all the references to the method you are changing. Once you are done modifying parameters you can preview your changes. The preview dialog shows you where Eclipse made changes and what they look like. If you are satisfied with the changes, click OK to confirm them.

With features like this, you can perform a good number of the "Making method calls simpler" refactorings from Fowler's book. With Change Method Signature you can do refactorings such as Rename Method, Add Parameter, Remove Parameter, and Introduce Parameter Object.

Generalization

The Push Down feature pushes a method or member variable of a class to its children, while the Pull Up feature pulls a method or member variable of a class to its super class. The Extracts Interface creates a Java interface from the methods of a class and makes that class implement the interface. This feature also changes the references of the class to the interface wherever possible. Generalize Type lets you use a parent of a member variable or a method return type. Eclipse automatically changes the references of that variable where possible. Use Super Type Where Possible tries to convert all the references to a class to its super class where this is possible.

I find the Pull Up feature particularly useful. It is handy to use when you realize that you can reuse a particular method if it only resided on the super class. To use Pull Up, you select a method or member variable by highlighting it. You can also just select a class. Then click on the Push Down menu item in the Refactor menu. The Pull Up dialog pops up (Figure 4), letting you select the methods or member variables you want to pull up. You can also select to what class in the inheritance tree you would like to pull these methods and member variables to. The default selection is the immediate super class. Once you are done, click Finish and Eclipse pulls your selections up.

The features in this section match nicely to the Dealing with Generalization refactoring patterns. With the Push Down feature, you can do Push Down Method and Push Down Field refactorings. With Pull Up, you can do Pull Up Field and Pull Up Method refactorings. And with Extract Interface, you can do the Extract Interface refactoring. Although not all of Eclipse's refactoring features match directly to a refactoring pattern, some are useful to do a part of a refactoring pattern; for example, if you want to perform an Extract Superclass refactoring. In Extract Superclass, you take the common methods and member variables of two or more classes and create a super class with these methods and member variables. Once you have the super class, Pull Up will be useful to insert the common methods in the super class.

Organizing Methods and Data

The Inline feature removes a selected method, variable, or constant from a class and places that code in all classes that were referencing it. The Extract Method feature creates a method from a selected section of code and inserts a call to that method were the code was. Extract Local Variable converts an expression such as new String("Test") into a member local variable and then replace the instances of that expression with the local variable. Extract Constant creates a constant from an expression such as 300+400 or 3.1415. Then it replaces all instances of the expression with the constant. Introduce Parameter makes an expression or local variable a parameter in the method signature that the expression belongs to. Introduce Factory makes the selected constructor private and creates a static factory method to instantiate the class. The Convert Local Variable to Field feature transforms a variable defined inside a method to a class member variable and makes the appropriate changes to the method code. Encapsulate Field creates getters and setters for a class member variable.

I use the Extract Method feature a lot. For example, usually when you are implementing an algorithm for the first time, the implementing methods are long and difficult to follow. So once you have the methods ready, you can use to the Extract Method feature to make the code more readable and easier to reuse. To use this feature, first select a section of code inside a method. Then from the Refactor menu, click on the Extract Method menu item. This pops up the Extract Method dialog (Figure 5) where you give the new method a name. You can also specify the access modifier for that method. Eclipse extracts the selected code and replaces it with a call to the new method.

Another feature from this set that I use a lot is Introduce Factory. Having a factory method for object instantiation gives you more control over how the clients will be instantiating that object. I can also return subclasses of that object with a factory method. To use Introduce Factory, just select a constructor in a class. Then from the Refactor menu click on the Introduce Factory menu item and the Introduce Factory dialog (Figure 6) pops up. In this dialog, you can specify the name of the factory constructor, the factory class, and whether to make the constructor that the factory method replaces private.

Many of the features of this section match directly to a refactoring pattern. You can use the Inline feature to do the Inline Method refactoring. In the same way, Extract Method can be used to the Extract Method refactoring. You can also use Extract Method to partially perform the refactoring Replace Temp with Query. In this case, you use the Extract method to create the query method and then you get rid of the temporary variables. Introduce Factory matches directly to the refactoring Replace Constructor with Factory Method. The Encapsulate Field feature also matches directly to the refactoring Encapsulate Field. Other features of this group can be used to partially do some refactoring patterns. This list does not include all the instances where you can use a feature to perform a particular refactoring from Fowler's book. I am sure there are many other ways to use these features to perform refactorings.

Supporting Features

Eclipse has a number of features that support the refactoring features, in addition to those described here. You can undo/redo a refactoring and, for most refactorings, you can see a preview of the results of a particular refactoring operation. Eclipse also provides keyboard shortcuts for some refactoring operations. For example, you can call Change Method Signature with Alt+Shift+C. Another interesting supporting feature is that you don't need to highlight a method or member variable to select it. You can just select that method or variable from the explorer window and then start a refactoring operation.

Eclipse has provided me with a strong set of tools to facilitate and automate refactoring operations. These features let us refactor faster and more efficiently. Still, refactoring tools are only one side of the necessary refactoring support. To refactor well and safely, you need a set of test that you can run every time you refactor, just to make sure you didn't break anything. Luckily, Eclipse also has a good set of testing tools with its support of JUnit (http://www.junit.org/). All in all, Eclipse has a solid set of features with its refactoring tools and JUnit support. With refactoring tool support like Eclipse's, there is no excuse not to refactor.

DDJ


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video