Java Reference
In-Depth Information
but you must also select other options, including whether the field or variable
should be final and where it should be initialized. The initialization option spec-
ifies the point at which the selected expression is assigned to the new field. The
exact options available during the refactoring vary depending on the circum-
stances, and local variables don't have the initialization or visibility options.
You can also use this refactoring to assign the result of an operation that isn't
being captured to a field or variable. For example, consider the following code frag-
ment, realizing that the remove method of movieList returns the item removed:
movieList.remove(3);
Select the line, or place your cursor anywhere on it, and execute the Introduce
Va r i a b l e refactoring. After entering a new name, you end up with something like:
Movie removedMovie = movieList.remove(3);
This operation is so handy, we find ourselves using this refactoring frequently as a
shortcut for creating and defining new variables, even when we know ahead of
time that we'll need them. IDEA does most of the typing for us, and it even picks
good variable names!
Another use of this refactoring is to convert existing fields to variables and
variables to fields. When you place your cursor on a local variable reference and
execute the Introduce Field refactoring, you promote the local variable to field
status, making it accessible throughout the class. This is handy when working with
Swing classes, where we find ourselves creating GUI components as local variables
at first and then promoting them to field variables when we need to work with
them further.
Converting direct field references to method calls
The command Refactor | Encapsulate Fields replaces all direct references to a
field variable with appropriate access methods. You don't need to select a partic-
ular field; just make sure your cursor is positioned inside the class you wish to
refactor. The refactoring dialog appears, as shown in figure 9.20.
The dialog lists all the fields in your selected class, along with some suggested
names for the getter and setter methods the refactoring will generate. Select the
fields you wish to encapsulate; you can modify the names of the methods if you
wish. A number of refactoring options are available—note that they affect all the
fields you're refactoring, not just the currently selected one:
 
 
 
Search WWH ::




Custom Search