我和我的同事討論了以下最佳實踐問題。
大多數函數/方法都以一些參數檢查開始。風格的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