Do you consider this technique “BAD”?

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

    First, if you just want an answer to whether this code structure or idiom is "bad", I would think it is. However, I think this is a symptom of bad decomposition rather than whether the code you have is "good" or "bad".

    I would think much better analysis and refactoring will have to be done to be able to further address the source of the problem, rather than looking just at the code. If you can do something like:

    if (condition1(...) && condition2(...) && condition3(...) && ... && conditionN(...)) {
        // code that ought to run after all conditions
    };
    // code that ought to run whether all conditions are met or not
    

    Then I think it would be more "readable" and more idiomatic. This way, you can make functions like:

    bool conditionN(...) {
        if (!real_condition) return false;
        // code that ought to run
        return true;
    };
    

    You get the benefit of better decomposition and help from the compiler to produce the necessary short-circuitry that &&'s will bring. The compiler might even in-line the code in the functions to produce better code than if you would doing the hand-coded loop.

提交回复
热议问题