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 practices like these? If you are aware of any book / article, please do share.
//Code 1
bool MyApplication::ReportGenerator::GenerateReport(){
bool retval = false;
do{
if (!isAdmin()){
break;
}
if (!isConditionOne()){
break;
}
if (!isConditionTwo()){
break;
}
if (!isConditionThree()){
break;
}
retval = generateReport();
} while(0);
return retval;
}
//Code2
bool MyApplication::ReportGenerator::GenerateReport(){
if (!isAdmin() || !isConditionOne() || !isConditionTwo() || !isConditionThree()){
return false;
}
return generateReport();
}
The clean code by Robert C. Martin is a nice book which deals with this. But, I guess that book is inclined towards Java.
UPDATE:
I have purposefully used do{ }while(0); loop as I did not wanted to use goto.
I wanted to get rid of so many if and break statements, so I proposed Code 2.
What I can see from the replies is a mixed set of responses for both the Code1 and Code2. There are people who prefer goto as well compared to Code 1 (which I thought was better).