我想知道是否可以通过调用之前提取的方法来替换某些代码。
例如,我有一个类似模式的类:
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 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
}
答案 0 :(得分:1)
可能比重新编写代码更好一点就是在新代码的整个主体上提取方法,并检查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(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);
}
然后,可能重命名第二个提取的方法。它与您最初的建议略有不同,但它可能更可靠。