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
Before | After |
---|---|
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
- In the editor, select the method code block to be extracted into the object.
- On the main menu, or from the context menu of the selection, choose .
- Select whether you want to create inner class, or anonymous class.
- 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.
- If you want to create an anonymous class, you should specify method's name.
- In the Parameters area select the variables that will be used as a parameters.
- Review Signature Preview and click OK.
Last modified: 29 November 2017