3 回答

TA貢獻1817條經驗 獲得超14個贊
如果您使用 Java 8 或更高版本,一個可能的解決方案是使用 lambda。您可以使用通用邏輯定義內部函數,該函數采用 Runnable 作為參數:
private void commonLogic(Runnable action)
{
if(nullCheckStuff) {
action.run();
} else {
//log error
}
}
那么你的原始函數看起來就像:
public void entryPoint1()
{
commonLogic(() -> { method1(); method2()});
}
public void entryPoint2()
{
commonLogic(() -> method2());
}
您可能還需要向commonLogic()函數添加更多參數以傳遞nullCheckStuff表達式和錯誤處理塊所需的數據。

TA貢獻1831條經驗 獲得超10個贊
如果您的方法還沒有太多參數,您可以這樣重構:
public void commonEntryPoint(..., boolean m1Condition) {
if(nullCheckStuff) {
if (m1Condition) {
method1(stuff);
}
method2(stuff);
} else {
//log error
}
}
干杯!

TA貢獻1847條經驗 獲得超11個贊
所以你的代碼是這樣的:
public void entryPoint1(...)
{
if(nullCheckStuff) {}
method1(stuff);
method2(stuff);
} else {
//log error
}
}
public void entryPoint2(...)
{
if(nullCheckStuff) {
method2(stuff);
} else {
//log error
}
}
您必須取出 if 塊并將其放入另一個函數中,比方說checkNullStuff():
public bool checkNullStuff(<object, string, whatever> condition, int entrypoint) {
bool everythingOk = true;
//checks if null
if(condition) {
return !everythingOk;
}
//executes common methods
method1(stuff);
//if not empty check what to do
switch(entrypoint) {
case 1:
method2(stuff);
break;
case 2:
method3(stuff);
break;
default:
everythingOk = false;
}
return everythingOk;
}
為什么我使用 switch 而不是 if,如果你的入口點增長并且需要執行更常見的方法和入口點函數:
public void entryPoint1(...)
{
// here we check if went wrong, otherwise the functions were executed
if(!checkNullStuff(nullCheckStuff, 1)) {}
// code for when nullCheckStuff was not what we exepected
}
}
添加回答
舉報