java - Eclipse/Java 中的重构 : Apply "Extract Method" (Alt+Shift+M) afterwards

标签 java eclipse refactoring

我想知道是否可以通过调用之前提取的方法来替换某些代码。

例如,我有一个具有类似模式的类:

public class ExtractMethodDemo {
    public void doSequence() {
        long n1; n2;
        // Compute and print count
        n1 = 70;
        n2 = compute(n1);                                        // <-- 1st
        System.out.printf("Input %4s, output = %s.%n", n1, n2);  // <-- occurrence
        ....
        // Compute and print count again
        n2 = n2 % 100;
        n1 = compute(n2);                                        // <-- Nth
        System.out.printf("Input %4s, output = %s.%n", n2, n1);  // <-- occurrence
    }
}

refactor using a method但由于某种原因,某些事件仍然没有被重构(如果未选中Replace other events...,或者如果稍后粘贴相同的代码,则可能会发生这种情况):

public void doSequence() {
    long n1; n2;
    // Compute and print count
    n1 = 70;
    n2 = doAll(n1);                                          // <--- method extracted
    // ....
    // Compute and print count again
    n2 = n2 % 100;
    n1 = compute(n2);                                        // <--- oops! this one is
    System.out.printf("Input %4s, output = %s.%n", n2, n1);  // <--- still old style
}

private long doAll(long n) {
    long n2; // (BTW: not the n2 declared in doSequence!)
    n2 = compute(n);
    System.out.printf("Input %4s, output = %s.%n", n, n2);
    return n2;
}

之后是否可以重构重排序列:

public void doSequence() {
    long n1; n2;
    // Compute and print count
    n1 = 70;
    n2 = doAll(n1);
    // ....
    // Compute and print count again
    n2 = n2 % 100;
    n1 = doAll(n2);    // <--- would be great to apply same refactoring afterwards
}

最佳答案

也许比重新内联代码更好一点的是在新代码的整个主体上提取方法,并选中替换其他出现,然后从原始调用中内联新方法。这样您就可以减少选择错误的行进行提取的风险。

更新:这是一个示例:

你从

开始
extractableCode(1);
extractableCode(2);
extractableCode(3);

并提取原始 block ,留下

extractedMethod(1);
extractableCode(2);
extractableCode(3);
...
function extractedMethod(int i) {
    extractableCode(i);
}

您的方法是内联extractedMethod,然后使用替换所有出现重复提取。我建议您从 extractedMethod() 内部提取:

extractedMethod(1);
secondExtractedMethod(2);
secondExtractedMethod(3);
...
function extractedMethod(int i) {
    secondExtractedMethod(i);
}
function secondExtractedMethod(int i) {
    extractableCode(i);
}

然后将原始调用内联到第一个提取的方法:

secondExtractedMethod(1);
secondExtractedMethod(2);
secondExtractedMethod(3);
...
function secondExtractedMethod(int i) {
    extractableCode(i);
}

然后,可能会重命名第二个提取的方法。它与您最初的建议只有一点点不同,但可能更可靠一些。

关于java - Eclipse/Java 中的重构 : Apply "Extract Method" (Alt+Shift+M) afterwards,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475489/

相关文章:

java - 如何在java中打开记事本文件?

java - 为什么以下代码在运行时不打印值?

refactoring - 哪些类名表明需要重构?

java - 如何在 JSP 中导入我的导入?

c# - 如何在没有 Moles 或 Isolator 的情况下对使用静态类的方法进行单元测试?

java - libGDX 不会在 android 上运行

java - 如何在 apache Camel 中使用 Splitter EIP 将 csv 文件一次拆分为 20 行?

java - 创建一个控制台菜单供用户进行选择

java - 更改 eclipse 中的 System.in 以从文件中读取

Eclipse Mars 不会自动导入 JavaFX