我和我的同事讨论了以下最佳实践问题。
大多数函数/方法都以一些参数检查开始。风格的if:嵌套或不嵌套
我主张以下风格,避免嵌套。
if (parameter one is ugly) return ERROR;
if (parameter two is nonsense || it is raining) return ERROR;
// do the useful stuff
return result;
他,谁来自更多的功能/逻辑编程背景,更喜欢下面的,因为它减少了从函数退出点的数量。
if (parameter one is ok) {
if (parameter two is ok && the sun is shining) {
// do the useful stuff
return result
}
}
return ERROR;
您更喜欢哪一个?为什么?
使用警卫条款的建议。检查Fowlers重构规则:http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html - 它将您的第二个(嵌套)转换为第一个(guard子句)。 – Konerak 2010-05-26 14:39:50