Replace temp with Query
The Replace Temp with Query refactoring lets you extract the variable's initializer expression into a method, and replace all references to the variable with the calls to the extracted method. The declaration of the variable will be removed and the query method can be used in other methods.
Instead of int size = getActualSize()
and using size throughout the code, we just operate with getActualSize()
method. Though the resulting code has more invocations, it is much cleaner and helps identify precisely where the bottlenecks in the code can appear.
In the editor, place the caret at the name of the local variable you want to refactor.
On the main menu,or on the context menu, select
.When selecting a local variable, make sure that its value is not modified later in the code. Otherwise the error message appears.
In the dialog that opens, specify the name for the extracted method and other options. For example, you can declare the method static, select parameters that will be used in the extracted method, and specify the visibility options.
Click OK.
Example
Before | After |
---|---|
public void method() {
String str ="str";
String aString = returnString().concat(str);
System.out.println(aString);
}
|
public void method() {
String str ="str";
System.out.println(aString(str));
}
private String aString(String str) {
return returnString().concat(str);
}
|