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
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.
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.
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.
bool MyApplication::ReportGenerator::GenerateReport()
{
return isAdmin()
&& isConditionOne()
&& isConditionTwo()
&& isConditionThree()
&& generateReport(); // Everything's ok.
}
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.