IntelliJ IDEA 2017.2 Help

Extract Method Object

The Extract Method Object refactoring moves method into a new class, converting all the local variables to its fields, allowing you to decompose the method into other methods on the same object. It is an alternative to the Extract Method, and can be used when you have multiple return values in an extracted method.

Example

BeforeAfter
class Account { int gamma (int val1, ...) { //some computations return c-2*a; } }
class Account { int gamma (int val1, ...) { Calculations calculations = new Calculations(val1, ...).invoke(); int c = calculations.getC(); int a = calculations.getA(); return c-2*a; } private class Calculations { private int val1; ... private int a; private int c; public Calculations(int val1, ...) { this.val1 = val1; ... } public int getA() {return a;} public int getC() {return c;} public Calculations invoke() { ...//computations return this; } } }

To extract a method object, follow these steps

  1. In the editor, select the method code block to be extracted into the object.
  2. On the main menu, or from the context menu of the selection, choose Refactor | Extract | Method Object.
  3. Select whether you want to create inner class, or anonymous class.
  4. If you want to create an inner class, you need to specify the name for the class and the visibility scope. You can also make the class static, if needed.
  5. If you want to create an anonymous class, you should specify method's name.
  6. In the Parameters area select the variables that will be used as a parameters.
  7. Review Signature Preview and click OK.
Last modified: 29 November 2017

See Also