Coding Standards / Coding Best practices in C++

前端 未结 17 1624
醉话见心
醉话见心 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.

    0 讨论(0)
  • 2021-01-02 09:31

    Regarding example 1: If you want goto, why don't you write goto??? It's much clearer than your suggestion. And considering that goto should only be used rarely, I vote for #2.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-02 09:37
    bool MyApplication::ReportGenerator::GenerateReport()
    {
       return isAdmin()  
          && isConditionOne() 
          && isConditionTwo()
          && isConditionThree()
          && generateReport();    // Everything's ok.
    }
    
    0 讨论(0)
  • 2021-01-02 09:37

    Personally I prefer sample 2. It groups those items that will not result in the report being generated together.

    As far as general coding guidelines, the book Code Complete (Amazon) is a good reference for coding style issues.

    0 讨论(0)
提交回复
热议问题