How to avoid multiple nested IFs

前端 未结 6 536
情话喂你
情话喂你 2021-02-01 19:08

I am currently trying to restructure my program to be more OO and to better implement known patterns etc.

I have quite many nested IF-statements and want to get rid of t

6条回答
  •  北海茫月
    2021-02-01 19:38

    It really depends on their purpose. In your first sample, the if statements serves the purpose of enforcing a contract, making sure that the input to the method meets certain requirements. In those cases, my own code tend to look pretty much like your code.

    In the case of using the if blocks to control the flow of a method (rather than enforcing a contract), it can sometimes be a bit harder. Sometimes I come across code like the following (extremely simplified) example:

    private void SomeMethod()
    {
        if (someCondition == true)
        {
            DoSomething();
            if (somethingElse == true)
            {
               DoSomethingMore();
            }
        }
        else
        {
            DoSomethingElse();
        }
    }
    

    In this case, it seems as if the method has several responsibilities, so in this case I would probably choose to split it into several methods:

    private void SomeMethod()
    {
        if (someCondition == true)
        {
            DoItThisWay();
        }
        else
        {
            DoSomethingElse();
        }
    }
    
    private void DoItThisWay()
    {
        DoSomething();
        if (somethingElse == true)
        {
           DoSomethingMore();
        }
    }
    

    This makes each method much simpler with less nested code, and may also increase the readability, if the methods are given good names.

提交回复
热议问题