IntelliJ IDEA 2018.1 Help

Extract method

The Extract Method refactoring lets you take a code fragment that can be grouped together, move it into a separated method and replace the old code with call to the method.

When you extract method you need to check for variables. If there is one output variable, it is used as a return value for the extracted method. In case there are multiple output variables, the Extract Method refactoring may not be applied, and the error message appears.

There are several workarounds to allow Extract Method work in this case. For example, you may introduce a special data-class that contains all output values.

  1. Select a code fragment you want to extract to a method.
  2. Press Ctrl+Alt+M or on the main menu, select Refactor | Extract | Method.
  3. In the dialog that opens, configure a method options, such as visibility, parameters, etc. You can also change a name of the method if you need. Click OK.
  4. If IntelliJ IDEA detects a duplicated code fragment that can be replaced with a call to extracted method, it will offer you to review your code and change it accordingly. If it is just one duplicate, IntelliJ IDEA will replace it silently, if there are more duplicates IntelliJ IDEA highlights the next duplicate that you can skip or replace via the Process Duplicate dialog.
    process duplicates
    Finally, if IntelliJ IDEA detects code that is only partially duplicated, it suggests you to extract a parameter in order to proceed with the refactoring.
    partial duplicates

Example

Let's extract the a+b expression into a method (function for Kotlin), and replace duplicates .

BeforeAfter
public void method() { int a=1; int b=2; int c=a+b; int d=a+c; }
public void method() { int a=1; int b=2; int c=add(a,b); int d=add(a,c); } ... private int add(int a, int b) { return a+b; }
BeforeAfter
fun method(){ val a = 1 val b = 2 val c = a + b val d = a + b }
fun method(){ val a = 1 val b = 2 val c = a + b val d = a + b } private fun add(a: Int, b: Int) = a + b
Last modified: 15 May 2018

See Also