Do you consider this technique “BAD”?

前端 未结 28 1493
借酒劲吻你
借酒劲吻你 2021-02-02 10:57

Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use exceptions for that, but exceptions generally are not

28条回答
  •  遇见更好的自我
    2021-02-02 11:38

    public bool Method1(){ ... }
    public bool Method2(){ ... }
    
    public void DoStuff(){
        bool everythingWorked = Method1() && Method2();
        ... stuff you want executed always ...
    }
    

    The reason why this works is due to something called short circuit logic. Method2 won't be called if Method1 returns false.

    This also has the additional benefit that you can break your method into smaller chunks, which will be easier to unit test.

提交回复
热议问题