Eclipse refactoring detailed (GO)

Source: Internet
Author: User
Tags visibility

Refactoring is an adjustment to the internal structure of software, which aims to improve its comprehension and reduce its modification cost without changing the software behavior. Developers can use a series of refactoring guidelines to adjust the structure of the software without changing the behavior of the software.

For a variety of reasons, developers should refactor code, such as poorly written code from previous developers, flaws in their previous designs, need to add new features or modify existing functionality, and so on. Martin Fowler, in his famous <<refactoring-improving the Design of Existing code>>, talks about several reasons why refactoring:

1. Refactoring can improve software design

Without refactoring, the program's design gets worse. Usually programmers only for short-term purposes, or in the absence of a complete understanding of the overall design, began to modify the code, so that the program will gradually lose their structure, programmers are increasingly difficult to read the original design by reading the source, I believe that every developer has deep experience.

The loss of the code structure is cumulative, the harder it is to see what the code represents, the harder it is to protect the design, and the more difficult the design will become, and the regular refactoring can help maintain the design.

2. Refactoring makes software easier to understand

Many developers think the code as long as it can be run up, I just started to do the development of the time is also said that, also wrote a lot of garbage code, and therefore ate a lot of pain.

Maybe some people may think that they may soon leave the position, do not care about the quality of the code, but as a developer, writing beautiful code is the most basic quality.

In the process of constantly modifying the software, the readability of the code will gradually accumulate, but it does not matter, as long as you remember to continue refactoring, you can make your code easier to understand.

3. Refactoring can help find bugs

The understanding of the code makes it easier to find bugs and, at the same time, to better understand the code and its behavior, as well as refactoring to help developers write stronger code.

4. Refactoring can improve the speed of programming

Good design is the fundamental of rapid software development, if there is no good design, perhaps the beginning of a period of time for developers to progress quickly, but the poor design will quickly slow down the development speed. Perhaps the time spent on debugging will be more and more, the time for modification will be more and more long, and this will be a vicious cycle.
Good design is fundamental to maintaining the speed of software development, and refactoring can help developers develop software faster because it prevents the system from deteriorating and improves the readability of the code.

Code refactoring with Eclipse

Refactoring is a very important means of ensuring code quality in the software development process, and it is easy to introduce some low-level errors (for example, misspelled words) by manually refactoring the code, resulting in a lot of unnecessary time wasted. Eclipse Refactoring provides strong support, and to a large extent, users don't have to worry about refactoring their clerical errors.
In Eclipse, you can refactor Java projects, classes, and their members using the refactoring capabilities provided by JDT, all of which can be seen as a JDT-aware Java element. To perform refactoring, you must first select the corresponding refactoring Java element, some refactoring is appropriate for any Java element, and some refactoring is only appropriate for a particular Java element, and almost all refactoring can see the effect of the preview in the Refactoring dialog box.

To use Eclipse's refactoring capabilities, you can select the appropriate Java elements (resources in Java engineering, including projects, files, methods, variables, and so on), and choose the refactoring function under the Refactor menu from the right-click menu, as shown in 1.

Figure 1 Selecting the Refactoring menu

In eclipse, refactoring can be easily divided into structural refactoring, class-level refactoring, and intra-class refactoring, and each type of refactoring contains specific implementations, and the next step is to explain how eclipse will refactor Java elements.

Tip: In the JDT recognizable range, you can assume that the resources in the project are Java elements, including Java file names, classes, methods, variables, and so on.

Structural refactoring

Structural refactoring involves changes in the physical structure of Java elements, including "Rename", "Move", "Change Method Signature", "Convert Anonymous Class to Nested", and "move Member Type to New File, the implementation of these refactoring in eclipse is described below.

1. Rename

The function of rename refactoring is to rename Java elements. Although you can manually modify the file name or other Java element name, this does not update the reference associated with this Java element, and the user must manually find the location associated with this Java element and then manually modify it. By manually modifying the name, the likelihood of clerical errors will increase. With the functionality of the rename provided by Eclipse, Eclipse automatically completes the operation of updating related references.
To preserve the readability of your code, you can rename Java elements with the refactoring capabilities of Eclipse, when the Java element is not clearly named or has changed functionality. Select the appropriate Java element and choose the Rename menu under the right-refactor menu to rename the currently selected element and modify the corresponding element name in the popup Rename dialog box, such as modifying the rename of a package, as shown in 2.

Figure 2 Rename dialog box

To modify the package name, you can choose whether to update references and update subdirectories, or even non-Java files that can optionally be updated. Selecting the Preview button previews the effect after renaming the refactoring, as shown in 3.

Figure 3 Previewing the rename package name

You can see whether the contents of the preview are consistent and confirm that you want to rename the refactoring. Java elements that can be renamed are Java projects, Java files, packages, methods, and attribute fields.

Tip: Non-Java projects and Java files can also be renamed using the Rename of the refactoring menu.

2. Move

The refactoring of move is similar to refactoring of rename, it can move a Java element from one place to another, and the refactoring of move is mainly used to move a class to a different package. First select a Java file, select the Move menu item under the Refactor menu, and pop Up the Move Refactoring dialog box, shown in 4.

Figure 4 Move dialog box

You can choose whether to update the reference and set some parameters for moving the file refactoring.

Tip: You can also drag a file from one package to another to achieve the refactoring of moving files.

3. Change Method Signature

The function of the "change method Signature" refactoring is to alter the definition of methods, such as changing the method's parameter name, type and number, the type of the return value, the visibility of the method, and the name of the method.

To change the definition of a method, you can select the method and select the "Change Method Signature" submenu item in the Refactor menu by the right-click menu, which pops up the "Change Method Signature" dialog box, shown in 5.

Figure 5 "Change Method Signature" dialog box

You can change the method's parameter name, type and number, the type of the return value, the visibility of the method, the method name, and so on, using the Signature dialog box.

4. Convert Anonymous Class to Nested

The function of "Convert Anonymous class to Nested" refactoring is to change the anonymous class to an inner class so that other parts of the same class can share the class as well.
For example, there are classes shown in routine 1.

Routine 1

public class Keylistenerexample {display display; Shell Shell; Keylistenerexample () {display = new display (); shell = new Shell (display); Shell.setsize (+); Shell.settext ("A Keyl Istener Example "); Text text = new text (Shell, SWT. BORDER); Text.setbounds (50, 50, 100, 20); Text.addkeylistener (New KeyListener () {public void keypressed (KeyEvent e) {System.out.println ("key Pressed-" + E.charac ter); } public void keyreleased (KeyEvent e) {System.out.println ("key released-" + E.character);}); (); while (!shell.isdisposed ()) {if (!display.readanddispatch ()) Display.sleep ();} display.dispose (); } public static void Main (string[] args) {new keylistenerexample ();}}

In the Keylistenerexample class has an anonymous class, implements the KeyListener interface, you can change the anonymous class to internal class, first select the anonymous class, right-click the Refactor "Convert Anonymous class to Nested" menu, enter the name of the inner class, as shown in 6.

Figure 6 "Convert Anonymous Class to Nested" dialog box

The result of the refactoring is that eclipse created an inner class named Testkeylistener, and the refactored code is shown in routine 2. after the reconstruction of routine 2

public class Keylistenerexample {Private Final class Testkeylistener implements KeyListener {public void keypressed (Keye Vent e) {System.out.println ("key Pressed-" + e.character), public void keyreleased (KeyEvent e) {System.out.println ("K EY released-"+ E.character); }} display display; Shell Shell; Keylistenerexample () {display = new display (); shell = new Shell (display); Shell.setsize (+); Shell.settext ("A Keyl Istener Example "); Text text = new text (Shell, SWT. BORDER); Text.setbounds (50, 50, 100, 20); Text.addkeylistener (New Testkeylistener ()); (); while (!shell.isdisposed ()) {if (!display.readanddispatch ()) Display.sleep ();} display.dispose (); } public static void Main (string[] args) {new keylistenerexample ();}}

You can also define the accessibility of the newly generated inner class through the Convert Anonymous class to Nested dialog box.

5. Move Member Type to Top level

With the "Move Member Type to Top level" refactoring, you can change the inner class to a non-intrinsic class and recreate a new file so that other classes can share the class.

Routine 2 creates an inner class testkeylistener that can now be refactored into a single class using the "Move Member Type to Top" refactoring method. First select the Testkeylistener class, and from the right-click menu Refactor Select "Move Member type to top level" and open the "Move Member type to top level" dialog box, shown in 7.

Figure 7 "Move Member Type to Top Level" dialog box

You can change the inner class to a non-intrinsic class by refactoring the "Move Member Type to top level" above.

Tip: Sometimes refactoring is not a step-by-step refactoring, for example, by first changing an anonymous class to an inner class and then changing the inner class to a non-intrinsic class.

Class-Level refactoring

Class-Level refactoring has the following:

1. Push Down

The "Push Down" refactoring feature moves the parent class's methods and properties to all subclasses, and the parent class's methods can selectively preserve the abstract method. First select the parent class, right-select the "Push Down" menu item in the Refactor menu, and select refactoring from the "Push Down" dialog box, shown in 8.

Figure 8 "Push down" dialog box

The "Push down" refactoring is useful when you redesign a class, and it can compare the inheritance of classes and clearly define the behavior of classes.

2. Pull Up

The "Pull up" refactoring is the opposite of the "Push Down" refactoring, which is to move methods and properties to their parent classes. Select the subclass you want to refactor, and from the right-click menu, select the Pull Up menu item from the Refactor menu, which is refactored with the Pull Up dialog box, shown in 9.

Figure 9 Pull Up dialog box

Tip: "Pull up" refactoring and "Push down" refactoring may cause errors, and when you use this refactoring, you should first clarify whether there are references to other methods or properties in some methods.

3. Extract Interface

The "Extract Interface" refactoring can extract interfaces from an existing class, and it can select a method from a class to extract the methods into a separate interface. Select the class that extracts the interface, right-select the Extract Interface menu item in the Refactor menu, and open the Extract Interface dialog box, shown in 10.

Figure "Extract Interface" dialog box

The unit OK button will extract the TestInterface interface, and after extracting the interface, the currently selected class will implement this interface.

Tip: Only public methods can be extracted as interfaces.

4. Generalize declared Type

The "Generalize declared type" Refactoring can change the types of variables, parameters, properties, and return values of functions, and it is possible to change these types to the type of their parent class. In the Refactor menu, select "Generalize declared Type", as shown in 11.

Figure One "Generalize declared Type" dialog box

Click the OK button to change the declared type to the type selected in the dialog box.

5. User supertype Where Possible

The "User supertype Where Possible" Refactoring is able to replace the type of the current class with the type of the parent class of a class and select the class that needs to be replaced by the reference. In the Refactor menu, select "User supertype where Possible" to open the "user supertype where Possible" dialog box, shown in 12.

Figure "User supertype Where Possible" dialog box

The "Generalize declared Type" refactoring and "User supertype where Possible" refactoring are useful for interface-oriented programming and can be implemented with interfaces as much as possible with referenced objects.

Tip: "User supertype Where Possible" Refactoring will replace references in other classes, and to see the effect of refactoring, you should find the location of other class references that will not modify the current file.

Intra-class refactoring

Class internal Refactoring has the following:

1. Inline

The "Inline" refactoring can replace the function's reference with the contents of the function. First select the function reference, and in the Refactor menu choose "Inline" to open the "inline" dialog box, shown in 13.

Figure "Inline" dialog box

Click the OK button, and Eclipse will replace the referenced part with the part of the method implementation, which is currently not in the way of a method call. You can also select "All Invocations" and "Delete method declaration", and Eclipse will replace the location of all referenced methods and delete the methods.

Tip: Inline replaces all calling methods with the implementation part of the method.

2. Extract Method

The "Extract method" refactoring and "Inline" refactoring, in contrast, can extract small methods from lengthy methods and break down large methods into smaller methods to make the code look more simple and beautiful, and to a great extent improve the reusability of the code. You can select the code that you want to extract the method from, and in the Refactor menu, choose Extract method to open the Extract Method dialog box, shown in 14.

Figure "Extract Method" dialog box

The refactoring of "Extract method" is a very good way to reconstruct the weight of a large method and make the code more understandable.

Hint: "Extract method" refactoring and "inline" refactoring are corresponding, sometimes in order to organize some of the non-function, you can first through the "inline" way to generate a large function, and then through the "Extract method" to reconstruct the large function, Make the code more reasonable.

3. Extract Local Variable

In the development process, it is very good to use variables instead of expressions, which makes the code easier to understand. In eclipse, you can use the Extract local Variable refactoring implementation to extract local expressions. First select the expression, and in the Refactor menu, choose Extract Local Variable to open the Extract local Variable dialog box, shown in 15.

Figure "Extract Local Variable" dialog box

4. Extract Constant

"Extract Constant" refactoring is similar to "Extract Local Variable" refactoring, which defines expressions as constants, and "Extract Constant" refactoring to set the visibility of constants. Select an expression, and in the Refactor menu, choose Extract Constant to open the Extract Constant dialog box, shown in 16.

Figure "Extract Constant" dialog box

5. Introduce Parameter

The "introduce Parameter" refactoring can add new parameters to a function through an expression, variable, or reference in a function, and can automatically update default parameters that refer to other locations of this function. To refactor introduce Parameter, you can select an expression, a variable, or a reference. In the Refactor menu, select "Introduce Parameter" to open the introduce Parameter dialog box, shown in 17.

Figure "Introduce Parameter" dialog box

6. Introduce Factory

The "Introduce Factory" refactoring enables you to create a factory method for a class. First select the constructor for the class that needs to create the factory method, and in the Refactor menu, choose Introduce Factory to open the introduce Factory dialog box, shown in 18.

Figure "Introduce Factory" dialog box

In the Introduce Factory dialog box, you can enter the name of the factory method and the factory class, and eclipse will automatically create a factory method based on the constructor function.
Tip: The factory class should already exist, you can usually create a factory method for multiple associated classes in a factory class, so you should create a factory class before using the introduce Factory refactoring.

7. Convert Local Variable to Field

The "Convert local Variable to Field" refactoring is able to convert local variables into global variables in a class. First select the local variable to convert, and in the Refactor menu choose "Convert local Variable to field" to open the "Convert local Variable to Field" dialog box, shown in 19.

Figure "Convert Local Variable to Field" dialog box

In the Convert Local Variable to Field dialog box, you can also modify the name of the variable and the visibility of the variable.

8. Encapsulate Field

The "Encapsulate Field" refactoring is able to wrap the accessibility of properties and generate access methods. First select the properties to wrap, and in the Refactor menu, choose Encapsulate field to open the Encapsulate Field dialog box, shown in 20.

Figure "Encapsulate Field" dialog box

The Get and set methods are usually generated through "encapsulate Field". You can enter the name of the access method for the property in the Encapsulate Field dialog box, as well as the location and visibility of the method generated by the method.

Tip: You can also generate the appropriate get and set methods by using the source menu of the right-click menu.

Undo and Redo

The automatic refactoring feature of Eclipse can support the renaming of various program elements and automatically update related references. Eclipse can support methods, fields move between classes, and automatically update references, better support for inline fields, function updates and replacements, and better support for extracting methods, variables and other program elements.

The process of refactoring is a process of continuous attempt and exploration. The refactoring of Eclipse supports undo and redo, and the ability to preview refactoring results is a useful feature. To perform undo and redo (undo and Redo) functions, you can press the shortcut key CTRL + Z and Ctrl+y, or you can choose the Undo and Redo actions of the Edit menu.

Tip: Although eclipse provides strong support for refactoring, testing of refactoring code is essential, and it is not expected that eclipse will be able to solve all the refactoring problems, and sometimes manual refactoring is necessary.  The idea of automatic refactoring should be "tool-assisted refactoring", but developers still assume a large part of the refactoring effort.

Eclipse refactoring detailed (go)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.