亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有好的方法來重構使用重復條件語句的方法?

有沒有好的方法來重構使用重復條件語句的方法?

翻過高山走不出你 2023-12-13 16:55:37
我有兩個類似的方法,具有重復的條件和重復的 else 塊。我想重構它以共享相同的邏輯和 else 塊,但調用不同的方法。我怎樣才能做到這一點?public void entryPoint1(...){    if(nullCheckStuff) {}        method1(stuff);        method2(stuff);    } else {        //log error    }}public void entryPoint2(...){    if(nullCheckStuff) {        method2(stuff);    } else {        //log error    }}
查看完整描述

3 回答

?
大話西游666

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表達式和錯誤處理塊所需的數據。


查看完整回答
反對 回復 2023-12-13
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

如果您的方法還沒有太多參數,您可以這樣重構:


public void commonEntryPoint(..., boolean m1Condition) {

    if(nullCheckStuff) {

        if (m1Condition) {

            method1(stuff);

        }

        method2(stuff);

    } else {

        //log error

    }

}

干杯!


查看完整回答
反對 回復 2023-12-13
?
回首憶惘然

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

    } 

}


查看完整回答
反對 回復 2023-12-13
  • 3 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號