IntelliJ IDEA 2021.1 Help

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.

  1. In the editor, place the caret at the name of the local variable you want to refactor.

  2. On the main menu,or on the context menu, select Refactor | Replace Temp with Query.

    When selecting a local variable, make sure that its value is not modified later in the code. Otherwise the error message appears.

  3. 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.

  4. Click OK.

Example

BeforeAfter
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); }
Last modified: 08 March 2021