Refactoring Your Code
Refactoring refers to the task of making mass changes to a project. For example, suppose you decide that a class name you created when you started the project doesn't really accurately describe the purpose of the class, so you want to change it. Simple text editors, such as TextPad, include a Replace command that lets you change occurrences of text strings within a file, but changing the name of a class requires that you change the name in all the files in a project.
Eclipse includes a whole menu of refactoring options-called, as you might guess, the Refactor menu. This menu contains more than 20 different types of refactoring commands. If you're just starting to learn Java, most of these commands won't make any sense to you. For example, the Refactor menu contains commands that let you change an anonymous inner class to a nested class, push members down to a subclass, or introduce a factory.
A few Refactor menu commands are especially useful as you work your way through the basics of learning Java. In particular, these:
-
Rename: Lets you rename a variable, method, or other symbol. First, select the symbol you want to rename. Then, choose Refactor
Rename, type the new name, and then click OK.
-
Extract Method: This command lets you create a separate method from one or more statements. Select the statements you want to place in the method, and then choose Refactor
Extract Method. In the dialog box that appears, type the name you want to use for the method. Eclipse creates a method with the statements you selected, and then replaces the original selection with a call to the new method.
-
Inline: This command is pretty much the opposite of the Extract Method command. It replaces a call to a method with the statements that are defined in the body of that method. This command is most useful in situations where you thought a method was going to be either more complicated than it turned out to be, or you thought you'd call it from more locations than you ended up calling it from.
-
Extract Local Variable: This one is weird. Sometimes you discover that you have a whole string of statements in a row that use a particular expression (say, x + 1). Wouldn't it be better if you just created a separate variable to hold the value x + 1, and then used that variable instead of repeatedly recalculating the expression? The Extract Local Variable command can do this for you. Highlight the first occurrence of the expression and choose Refactor
Extract Local Variable. Eclipse creates a local variable, adds an assignment statement that assigns the expression to the new local variable, and then replaces all occurrences of the expression with the local variable.
No comments:
Post a Comment