[英]Is there a way to combine two methods that have the same body and return type but different parameters?
[英]Best way to refactor methods that have the same code but different return values
我有這段代碼:
public A methodA(X answer) {
...
return A;
}
public B methodB(X answer) {
...
return B;
}
所以,例如,我有兩個在不同的方法中調用那些方法,因為返回類型不同,所以例如在控制器上:
public A version1(X answer) {
...
A ant = methodA();
...
}
public Bversion2(X answer) {
...
B bee = methodB();
...
}
關鍵是其他每一行代碼都是相同的,除了指定的調用。 如何在 Java 中重構此代碼以避免使用重復代碼?
我會將代碼的唯一部分提取到Supplier
,將公共代碼移動到一種方法,並讓原始方法與供應商一起調用該底層方法:
public A version1(X answer) {
return unversioned (answer, this::methodA);
}
public B version2(X answer) {
return unversioned (answer, this::methodB);
}
private <T> T unversioned(X answer, Supplier<T> supplier) {
// Some code before the supplier
T result = supplier.get();
// Some code after the supplier, that may interact with the result
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.