程式碼註釋中的5要與3不要

釋懷發表於2015-06-04
不要重複閱讀者已經知道的內容
能明確說明程式碼是做什麼的註釋對我們是沒有幫助的。
// 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
}
要把長註釋放在邏輯上面,短註釋放在後面
註釋如果不超過120個字元那可以放在程式碼旁邊。否則,就應該直接把註釋放到語句上面。
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
}
註釋要拼寫正確
不要為程式碼註釋中的拼寫錯誤找藉口。IDE可以為你檢查拼寫。如果沒有這個功能,那就去下載外掛,自己動手!
要多多練習
熟能生巧。試著寫一些有用的註釋,可以問問其他開發人員你的註釋是否有用。隨著時間的推移,你會慢慢懂得怎樣才算是友好的註釋。
要審查別人的註釋
在程式碼審查時,我們往往會忽略檢視註釋。不要怕要求更多的註釋,你應該提出質疑。如果每個人都養成寫好註釋的好習慣,那麼世界將會更美好。
總結
註釋是開發程式中非常重要的一部分,但我們不應該為了註釋而註釋。註釋應該是有用的,簡潔的,應該是對程式碼的一種補充。註釋不應該用於逐行地解釋程式碼,相反,它應該用於解釋業務邏輯,推理以及對將來的啟示。
相關閱讀
評論(1)

相關文章