Coding Standards / Coding Best practices in C++

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

    I like the answers that are a variation of version 2, but just to give an alternative: If those conditions are logically tied together, chances are that you will need to check for them again in other places. If this is true, then maybe a helper function would do the job better. Something like this:

    bool isReportable(anyParametersNeeded){
        //stuffYouWantToCheck
    }
    
    bool MyApplication::ReportGenerator::GenerateReport(){
        if (isReportable(anyParametersNeeded)){
            return generateReport();
        }
        return false;
    }
    

    As this function is small, maybe you can even inline it (or let the compiler decide ;)). Another bonus is that if you want to include some extra checks in the future, you only have to change that function and not every spot where it's used.

提交回复
热议问题