簡體   English   中英

拋出異常而不是處理退貨

[英]Throwing exception instead to deal with returns

我試圖重構一英里長的方法,並考慮拋出一個ReturnException而不是調用返回。 看我的例子:

當前里程長代碼如下所示:

  public void MyMileLongMethod()
  {
        //some logic
        //some more logic

        if (a == 10 && (b == "cool" || b == "super cool"))
        {
            //logic here 
            //more logic
            //15 more lines of code. 
            return;
        }

        if (x && y || z==5)
        {
            //logic here 
            //more logic
            //20 more lines of code. 
            return;
        }
        //more conditions like this that calls a return
        // probable more logic here
    }

我想用以下方式重構它:

    public void MyRefactoredMethod()
    {
        try
        {
            DoLogic1(parameters);

            ConditionOneMethod(parameters);

            ConditionTwoMethod(parameters);

            //more methods like above that throws a ReturnException
            // probable more logic here
        }
        catch (ReturnException)
        {
            return;
        }
    }
    void DoLogic1(parameters)
    {
        //some logic
        //some more logic
    }

    void ConditionOneMethod(parameters)
    {
        if (a == 10 && (b == "cool" || b == "super cool"))
        {
            //logic here 
            //more logic
            //15 more lines of code. 
            throw new ReturnException();
        }
    }

    void ConditionTwoMethod(parameters)
    {
        if (x && y || z == 5)
        {
            //logic here 
            //more logic
            //20 more lines of code. 
            throw new ReturnException();
        }
    }

問題:拋出一個異常並在一個調用方法中捕獲它,然后在catch中調用返回一個好的做法? 如果,那么有一個常用的模式名稱嗎? 如果這不是一個好習慣,還有其他方法嗎? 或者我的解決方案是下面的答案嗎?

我的另一個解決方案是,檢查外部方法中的條件,然后調用執行邏輯的方法,然后調用return,但這看起來在外部方法中有很多代碼。

我贊成使用這種變體:

private void MyRefactoredMethod(...) {
    ...
    if (...)
        return; // was "continue;"
    ...
    if (!ConditionOneMethod(...))
        return;
    ...
}

private boolean ConditionOneMethod(...) {
    ...
    if (...)
        return false; // was a continue from a nested operation
    ...
    return true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM