在 Eclipse/Java 中重构:之后应用"Extract Method" (Alt+Shift+M)



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

例如,我有一个具有类似模式的类:
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
    }
}

我使用一个方法进行重构,但由于某些原因,某些事件仍然没有重构(如果Replace additional occurrences...未选中,或者稍后粘贴相同的代码,则可能):

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
}

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

更新:这里有一个例子:

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

并提取原始块,留下

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

您的方法是内联extractedMethod,然后使用Replace All Occurrences重复提取。我建议你从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);
}

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

最新更新