The Extract Delegate refactoring lets you extract some of the fields and methods of a class into a separate, newly created class. This refactoring is useful, when a class has grown too large and "does too many things". In such cases, it might be a good idea to split the class into smaller, more cohesive classes.
Example
| Before | After |
|---|---|
public class Foo { private String b; public String getInfo() { return ("(" + b + ")"); } ... } public class Bar { Foo foo; String t2 = foo.getInfo(); ... } |
public class Foo { private final Info info = new Info(); public String getInfo() { return info.getInfo(); } ... } public class Info { private String b; public Info() {} public String getInfo() { return ("(" + b + ")"); } } public class Bar { Foo foo; String t2 = foo.getInfo(); ... } |
- Open the class in the editor, or select it in the Project tool window.
- Select from the main or the context menu.
- In the Extract Class dialog that opens:
- Specify the name and package for the class to be created.
- Selects the fields and methods to be included in the new class.
- Click Preview to see the usages of the selected fields or methods in the Find tool window. Select the usages to be included in the refactoring and click Do Refactor.