Coding Standards / Coding Best practices in C++

前端 未结 17 1730
醉话见心
醉话见心 2021-01-02 09:06

Consider the two code segments below. Which one is better and Why? If you have any other idea, please do mention. Where can I find answers to coding p

17条回答
  •  梦毁少年i
    2021-01-02 09:27

    Code Complete is a commonly recommended book that goes into some detail about those kinds of stylistic issues. Also consider taking a look at some of the published organization style guides to see if they have any opinions on the issue; Google's Style Guide, for instance.

    As to what I prefer, the second example is much better to my mind. The first is essentially an abuse of the do {} while construct to avoid using a goto, dogmatically sticking to the letter of "avoid gotos at all cost" while missing its spirit of "code for clarity, don't use unobvious language tricks".

    In fact, the only reason to even use a goto at all would be to dogmatically stick to a "only one return statement per function" approach when you could get away with a simple, readable

    if (!isAdmin()){
        return false;
    }
    else if (!isConditionOne()){
        return false;    }
    else if (!isConditionTwo()){
        return false;    }
    else if (!isConditionThree()){
        return false;    }
    else
        return generateReport();
    

    Other thoughts?

    Don't name local variables that are used to hold a computed success state "returnValue" or similar. Obviously whatever you return is the return value, any one who can read C can see what is being returned. Tell me what computation it holds. The name "returnValue" gives me no information as to what it means when it is true or false. In this example "couldGenerateReports" or similar would be far more preferable.

提交回复
热议问题