Extract Method Refactoring Improved in IntelliJ IDEA 14.1

<Extract method refactoring> turns a fragment into a method whose name explains the purpose of the method.

Martin Fowler

When we select a block of code, IntelliJ IDEA’s data flow analysis engine is able to deduce all local variables and parameters that are used inside, but are declared outside of it. These variables form the initial set from which a parameter list of the extracted method is be constructed:

Initial set is {i}, and the extracted method will have a signature such as newMethod(int i) .

So far, so good. Now, what if some parameters are always grouped together inside the code block?

We could derive a new parameter set {str} from an initial one {args, i}, where str = args[i]. IntelliJ IDEA does this under the hood, and the resulting set is configurable via the “Fold parameters” check-box:

extract_refactoring

The same result may be achieved by following these steps:

  1. Extract the method with parameters (args, i).

  2. Apply “Extract parameter” to args[i], accept the suggestion to replace all occurrences, and delete the unused parameters args and i.

These exact steps (possibly in reverse order) are performed on replacing duplicates when the initial selection does not contain the necessary variables:

At first step the selection is replaced with a newMethod() call, whose initial parameter set is empty. Then after “Hello, ” string is extracted as a parameter, the remaining line System.out.println(“World”) may be replaced with the newMethod(“World”) call.

This observation was inspiring. What if IntelliJ IDEA could do it automatically in the same way it detects that parameters could be folded together? You asked and we’ve delivered: IntelliJ IDEA 14.1 EAP detects duplicates in the code that may accept different values as parameters and shows this suggestion:

extract_refactoring_2

There is one more possibility to find hidden duplicates. Suppose we have this code:

The initial parameters set is also empty. If you simply extract the method, you’ll get the same suggestion as shown above, but you will also be asked if you’d like to make the extracted method static by passing field(s) as parameter. Again, exactly the same modification could be performed in two steps: “Extract Method” followed by “Make Method Static”, passing fields as parameters. This is just a small enhancement that can make our lives a little bit easier.

To try the improved version of Extract Method, download the latest IntelliJ IDEA 14.1 EAP build. Give us your feedback on the discussion forum and/or in our issue tracker. Thanks!

Develop with Pleasure!

This entry was posted in EAP Releases, New Features and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *