有没有办法让Intellij在我刚刚提取参数时用方法替换重复代码?

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

如果我运行重构提取一个方法,intellij有时会注意到有类似的代码可以用这个新方法替换。在很多情况下,我的下一步是提取一个参数,现在可以使用这种方法的地方更多了。但是,当我提取参数时,intellij 不会检查是否有新的代码重复项。有办法吗?

第 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
    }

}

第 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
    }

}

第 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);
    }

}

正如评论所说,如何让intellij实现它现在可以调用print("foo");

提取方法后,IntelliJ 不够智能,无法根据提取的参数找出类似的重构。正如您所发现的,它只会将参数提取到提取方法的现有 个调用者中。

在您的第 1 步中,尝试通过像这样更改 bar() 来提前设置您的提取方法:

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

然后在第 2 步中,IntelliJ 已经足够聪明,可以计算出所有类似的重构。

如果您因为第一个提取方法重构已经完成并提交而坚持第 2 步作为起点,请将我上面所说的应用到 print() 方法(从中提取方法),你应该能够达到相同的结果。然后你只需删除剩余的零参数 print().