CH7, Making Control Flow Easy to Read
The Order of Arguments in Conditionalsif (a > b) 左側通常是會有變化數值, 右側是比較基準, 通常是常數,
如 if (length >= 10) 會比下面這行容易閱讀 if (10 <= length)
returning early from a function 與 minimize nesting
盡量讓function提早返回與減少巢狀結構可以增加閱讀性, 如
if (do_auth() != true) {
do_auth_failed();
return;
}
if (permission_check() != SUPER) {
do_permission_check_failed();
return;
}
do_something();
會比下面寫法容易閱讀
if (do_auth() == true) {
if (check_permission() == SUPER) {
do_something();
} else {
do_permission_check_failed();
{
} else {
do_auth_failed();
}
-
參考資料:
- The Art of Readable Code

沒有留言:
張貼留言