我想知道是否可以通过调用之前提取的方法来替换某些代码。
例如,我有一个具有类似模式的类:
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/