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.
//代码1
@H_404_14@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; }//代码2
@H_404_14@bool MyApplication::ReportGenerator::GenerateReport(){ if (!isAdmin() || !isConditionOne() || !isConditionTwo() || !isConditionThree()){ return false; } return generateReport(); }Robert C. Martin的干净代码是一本很好的书,涉及到这一点.但是,我猜这本书倾向于Java.
更新:
>我有意使用do {} while(0);循环,因为我不想使用goto.
>我想摆脱这么多if和break语句,所以我提出了代码2.
从答复中我可以看到,对于Code1和Code2来说,这是一组混合的响应.有些人喜欢goto与代码1(我认为更好)相比.