Daniel Kaplan
Daniel Kaplan

Reputation: 67310

Is there a way to get Intellij to replace duplicate code with a method when I just extracted a parameter?

If I run the refactoring to extract a method, intellij will sometimes notice that there is similar code that could be replaced with this new method. In a lot of situations, my next step is to extract a parameter and now there are even more places that this method could be used. But, when I extract a parameter, intellij doesn't check to see if there are new code duplicates. Is there a way to do this?

Step 1

package mavensandbox;

public class Main {


    public void foo() {
        System.out.println("foo");
    }

    public void bar() {
        System.out.println("bar");  //I will extract method for this line
    }

}

Step 2

package mavensandbox;

public class Main {


    public void foo() {
        System.out.println("foo");
    }

    public void bar() {
        print();
    }

    private void print() {
        System.out.println("bar");  //doh, I wanted "bar" to be a parameter, that's the next step
    }

}

Step 3

package mavensandbox;

public class Main {


    public void foo() {
        System.out.println("foo");  //ok, so how do I get intellij to realize it can now call print("foo"); instead?
    }

    public void bar() {
        print("bar");
    }

    private void print(String s) {
        System.out.println(s);
    }

}

As the comment says, how do I get intellij to realize it can now call print("foo");?

Upvotes: 4

Views: 2842

Answers (1)

gknicker
gknicker

Reputation: 5569

Once the method has been extracted, IntelliJ isn't smart enough to figure out similar refactorings based on extracting a parameter. As you've discovered, it would extract the parameter only into existing callers of the extracted method.

In your step 1, try setting up for your extract method in advance, by altering bar() like this:

public void bar() {
    String s = "bar";
    System.out.println(s); // extract method for this line
}

then in step 2, IntelliJ will already have been smart enough to figure out all the similar refactorings.

If you're stuck with step 2 as a starting point because the first extract method refactoring has already been done and committed, apply what I said above to the print() method (extract method from it), and you should be able to achieve the same result. Then you'd just delete the leftover zero-param print().

Upvotes: 4

Related Questions