Do you consider this technique “BAD”?

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

    You can use exceptions for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations.

    Nothing's wrong with using exceptions. Exceptions are part of application logic. The guideline about exceptions is that they should be relatively rare at run time.

    0 讨论(0)
  • 2021-02-02 11:51

    I would consider this bad practice. I think it would be more idiomatic, and generally clearer if you made this a function and changed the breaks to returns.

    0 讨论(0)
  • 2021-02-02 11:51

    What about a functional approach?

    
            void method1()
            {
                ... some code
                if( condition )
                    method2();
            }
    
            void method2()
            {
                ... some more code
                if( condition )
                    method3();
            }
    
            void method3()
            {
                ... yet more code
                if( condition )
                    method4();
            }
    
    0 讨论(0)
  • 2021-02-02 11:52

    I would say your solution can be the right solution, but it depends. Paul Tomblin has posted an answer that is better (a series of if tubes) ... if it can be used.

    Paul's solution cannot be used when there are expensive object initializations along the way through your loop. If the created objects are used in later steps, the do while (0) solution is better.

    That said, variable naming should be improved. Additionally, why reuse the "escape" variable so much? Instead trap each individual error condition explicitly and break the loop so that it is obvious what causes the break out at each point.

    Someone else suggested using function calls. Again, this may not be an ideal decomposition if it adds unneeded complexity to the function calls due to the number of args that might be passed at any given step.

    Others have suggested this is a difficult to understand idiom. Well, first you could put a comment as suggested at the top of the loop. Second, do-while(0) is a normal and common idiom in macros that all C programmers should recognize immediately, so I just don't buy that.

    0 讨论(0)
提交回复
热议问题