Coding Standards / Coding Best practices in C++

前端 未结 17 1723
醉话见心
醉话见心 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条回答
  •  执念已碎
    2021-01-02 09:33

    I prefer a modification of sample 2:

    bool MyApplication::ReportGenerator::GenerateReport()
    {
        bool returnValue = false;
        if (isAdmin() &&
            isConditionOne() &&
            isConditionTwo() &&
            isConditionThree())
        { 
            returnValue = generateReport();
        } 
        return returnValue;
    }
    

    It has the benefit of having a single exit point for the function, which is recommended for easier maintenance. I find stacking conditions vertically instead of horizontally easier to read quickly, and it's a lot easier to comment individual conditions if you need to.

提交回复
热议问题