Do you consider this technique “BAD”?

前端 未结 28 1527
借酒劲吻你
借酒劲吻你 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:31

    What you're trying to do is non-local failure recovery. This is what goto is for. Use it. (actually, this is what exception handling is for -- but if you can't use that, 'goto' or 'setjmp/longjmp' are the next best thing).

    This pattern, the if(succeeded(..)) pattern, and 'goto cleanup', all 3 are semantically and structurally equivalent. Use whichever one is most common in your code project. There's much value in consistency.

    I would caution against if(failed(..)) break; on one point in that you're producing a surprising result should you try to nest loops:

    do{
       bool isGood = true;
       .... some code
       if(!isGood)
           break;
       .... some more code
       for(....){
          if(!isGood)
              break; // <-- OOPS, this will exit the 'for' loop, which 
                     //  probably isn't what the author intended
          .... some more code
       }
    } while(false);
    ..... some other code, which has to be executed.
    

    Neither goto cleanup nor if(succeeded(..)) have this surprise, so I'd encourage using one of these two instead.

提交回复
热议问题