C编码标准/编码C的最佳实践
发布时间:2020-12-16 03:15:39 所属栏目:百科 来源:网络整理
导读: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 bool
//代码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; } //代码2 bool MyApplication::ReportGenerator::GenerateReport(){ if (!isAdmin() || !isConditionOne() || !isConditionTwo() || !isConditionThree()){ return false; } return generateReport(); } Robert C. Martin的干净代码是一本很好的书,涉及到这一点.但是,我猜这本书倾向于Java. 更新: >我有意使用do {} while(0);循环,因为我不想使用goto. 从答复中我可以看到,对于Code1和Code2来说,这是一组混合的响应.有些人喜欢goto与代码1(我认为更好)相比. 解决方法
我不太喜欢以这种方式使用do / while循环.另一种方法是将Code2中的条件分解成单独的检查.这些有时被称为“保护条款”.
bool MyApplication::ReportGenerator::GenerateReport() { if (!isAdmin()) return false; if (!isConditionOne()) return false; // etc. return generateReport(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |