mercredi 9 janvier 2019

Throwing exception instead to deal with returns

I am trying to refactor a mile long method and was thinking if throwing a ReturnException instead of calling the return. See my example:

Current mile long code looks like this:

  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
    }

And I would like to refactor it with a following way:

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

Question: Is throwing an exception and catching it in a method that calls, and then call the return in catch a good practice? If, so is there a commonly used pattern name for this? If this is not a good practice, is there any other way of doing it? Or is my solution below is the answer?

The other solution I have is, checking the conditions in the outer method and then call the method that does the logic and then call return, but that looks to me to much code in the outer method.

Aucun commentaire:

Enregistrer un commentaire