代码之家  ›  专栏  ›  技术社区  ›  Dilshod

处理异常而不是抛出返回

  •  4
  • Dilshod  · 技术社区  · 7 年前

    我正在尝试重构一英里长的方法,并考虑是否抛出一个ReturnException而不是调用return。请看我的示例:

    当前一英里长的代码如下所示:

      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();
            }
        }
    

    如果这不是一个好的做法,有没有其他办法呢?或者我的解决方案就是下面的答案?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Daler    7 年前

    我赞成使用这种变体:

    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;
    }