程式碼註釋,可以說是比程式碼本身更重要。這裡有一些方法可以確保你寫在程式碼中的註解是友善的:
不要重複閱讀者已經知道的內容
能明確說明程式碼是做什麼的註解對我們是沒有幫助的。
// If the color is red, turn it green if (color.is_red()) { color.turn_green(); }
要註釋說明和歷史
如果程式碼中的業務邏輯以後可能需要更新或更改,那就應該留下註釋:)
/* The API currently returns an array of items even though that will change in an upcoming ticket. Therefore, be sure to change the loop style here so that we properly iterate over an object */ var api_result = {items: ["one", "two"]}, items = api_result.items, num_items = items.length; for(var x = 0; x < num_items; x++) { ... }
同一行的註釋不要寫得很長
🀎 『水平滾動條來閱讀註解更令開發人員髮指的了。事實上,大多數開發人員都會選擇忽略這類註釋,因為讀起來真的很不方便。function Person(name) { this.name = name; this.first_name = name.split(" ")[0]; // This is just a shot in the dark here. If we can extract the first name, let's do it }
if (person.age < 21) { person.can_drink = false; // 21 drinking age /* Fees are given to those under 25, but only in some states. */ person.has_car_rental_fee = function(state) { if (state === "MI") { return true; } }; }
if (person.age >= 21) { person.can_drink = true; // A person can drink at 21 person.can_smoke = true; // A person can smoke at 18 person.can_wed = true; // A person can get married at 18 person.can_see_all_movies = true; // A person can see all movies at 17 //I hate babies and children and all things pure because I comment too much }