Coding Standards / Coding Best practices in C++

前端 未结 17 1722
醉话见心
醉话见心 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:30

    I would personally prefer a variation on your second code segment. The short circuiting will work the same, but the conditional is less verbose.

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

    It says everything in one nice clean spot. "If all these conditions are met, then do this. Otherwise, don't."

    I feel like your first code segment makes that logic harder to see by spreading the condition across 12 lines. Also, the encasing loop might cause someone to do a double take.

提交回复
热议问题