Java Reference
In-Depth Information
are assigned values or referenced in the selected block. If a variable or variables
are used only in the block, they're converted into the new method parameters. If
a variable is assigned inside the selection and used later in the code flow, this vari-
able determines the return type of the method. If you have several such variables,
IDEA prompts you about the impossibility of having multiple output values. If no
variables are assigned in the block, the new method has the void return type.
IDEA does a good job of naming the new parameters, but you can specify your
own names if you wish, and reorder the method parameters to your liking. You
can disable any of the parameters, in which case IDEA provides its own local vari-
able replacements with default values that probably aren't what you want. You
must go into the code and initialize them to appropriate values.
Converting a local variable reference to a method call
This refactoring operation lets you extract a local variable's initialization expres-
sion into a method and then replace all references to the local variable with the
new method call. To perform this operation, select the variable you wish to
replace, and execute the Refactor | Replace Temp with Query command from
the main menu. The resulting dialog is similar to that used during the Extract
Method refactoring discussed earlier. You can choose a name for the method as
well as the names and order of any parameters it requires.
Even though the end result may be more method invocations, the resulting
changes make the code cleaner. The resulting difference in speed is negligible if
the initialization is a simple expression or access method. If the initialization step
is computationally expensive, however, it may be best to retain the local variable,
in effect caching the results of the expensive operation. Besides, local variables
live on the stack and are therefore the fastest way to access data in the VM .
Replacing a constructor with a factory method
This refactoring converts an existing class constructor to a static factory method.
A static factory method is a static method that returns an instance of the class you
wish to create. Factory methods have three advantages over constructors that
make them worth considering as an alternative. First, you can name them what-
ever you want, so if you have several different ways of creating your object, you
can give them distinctive names. Second, static factory methods don't have to be
members of the class they're constructing. This lets you group methods for con-
structing related classes together. And finally, factory methods can return one of
many different concrete classes by declaring a return value of a common base
 
 
 
 
 
 
Search WWH ::




Custom Search