Extract into class refactorings
IntelliJ IDEA lets you use refactorings that extract fields, methods, and parameters into a new class. These refactorings are useful when a class has grown too large and "does too many things". In such cases, it may be a good idea to split the class into smaller, more cohesive classes.
Select a code fragment that you want to extract into a class.
Depending on what you want to extract, go to one of the following:
Refactor | Extract | Delegate
Refactor | Extract | Method Object
Refactor | Extract | Parameter Object
In the dialog that opens, specify the name of a new class, method and parameter options.
Preview your changes and click OK.
The Extract Delegate refactoring lets you extract some of the fields and methods of a class into a separate, newly created class.
tip
The Extract Delegate refactoring can also be accessed from a UML Class diagram.
Before | After |
---|---|
|
|
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.
note
You cannot extract the method object into an anonymous class, if the selected method code block contains local variables that should be accessed individually somewhere else. In this case, the method object can be extracted into inner class that will contain needed getters.
Before | After |
---|---|
|
|
The Extract Parameter Object refactoring lets you select a set of parameters to a method, and either create a wrapper class for those parameters, or use an existing compatible wrapper class. All calls to the method selected will have their parameters appropriately wrapped, and all usages of the wrapped parameter will be replaced by the appropriate calls on the newly created parameter class.
Before | After |
---|---|
|
|
Thanks for your feedback!