簡體   English   中英

在Eclipse / Java中進行重構:之后應用“提取方法”(Alt + Shift + M)

[英]Refactoring in Eclipse/Java: Apply “Extract Method” (Alt+Shift+M) afterwards

我想知道是否可以通過調用較早提取的方法來替換某些代碼。

例如,我有一個具有類似模式的類:

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

您的方式是內聯extractMethod,然后使用Replace All Occurrences重復提取。 我建議您改為從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);
}

然后,可能重命名第二個提取的方法。 它與您最初建議的僅稍有不同,但可能會更可靠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM