代碼注釋中的5要與3不要
代碼注釋,可以說是比代碼本身更重要。這里有一些方法可以確保你寫在代碼中的注釋是友好的:
不要重復閱讀者已經知道的內容
能明確說明代碼是做什么的注釋對我們是沒有幫助的。
- // 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可以為你檢查拼寫。如果沒有這個功能,那就去下載插件,自己動手!
要多多練習
熟能生巧。試著寫一些有用的注釋,可以問問其他開發人員你的注釋是否有用。隨著時間的推移,你會慢慢懂得怎樣才算是友好的注釋。
要審查別人的注釋
在代碼審查時,我們往往會忽略查看注釋。不要怕要求更多的注釋,你應該提出質疑。如果每個人都養成寫好注釋的好習慣,那么世界將會更美好。
總結
注釋是開發進程中非常重要的一部分,但我們不應該為了注釋而注釋。注釋應該是有用的,簡潔的,應該是對代碼的一種補充。注釋不應該用于逐行地解釋代碼,相反,它應該用于解釋業務邏輯,推理以及對將來的啟示。