Skip to content
無瑕的程式碼 Clean Code
Share
Explore

icon picker
註解

適當的使用註解是用來「彌補我們用程式碼表達意圖的失敗」

3.1 註解無法彌補糟糕的程式碼

會想寫註解的其中一個動機,大概就是程式碼寫得太糟了,為避免困惑,而「添加註解」來幫助人們理解。
而擁有「簡潔又具表達力註解」的程式碼 會優於「雜亂複雜滿是註解」的程式碼。

下面先來看看一個例子:
/** 1 */
// 確認員工是否有資格獲得全部福利
if(employee.flags & HOURLY_FLAGS) && (employee.age > 65){
......
} else {
......
}

/** 2 */
if(employee.isEligibleForFullBenefits()){
......
} else {
......
}
你覺得哪個寫法比較好?
從上面的 Code 我們可觀察到:
1 的條件判斷式內放了太多細節?
由於判斷式不夠精簡,導致需要寫額外的註解去解釋區塊內的行為
能否一眼看出 else 成立的條件?
65 這個年齡的意義為何? 若不懂「退休制度」的人看到 65 可能會很困惑

補充:
把 2 擴寫一下,可能就會變成這樣
RETIRE_AGE_LIMIT = 65;

if(employee.isEligibleForFullBenefits()){
......
} else {
......
}

isEligibleForFullBenefits(): boolean {
const isApplyRetire = employee.flags & HOURLY_FLAG;
const isEligibleForRetire = employee.age > RETIRE_AGE_LIMIT;

return isApplyRetire && isEligibleForRetire;
}
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.