中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

代碼注釋中的5要與3不要

2018-07-20    來源:編程學(xué)習(xí)網(wǎng)

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用

  代碼注釋,可以說是比代碼本身更重要。這里有一些方法可以確保你寫在代碼中的注釋是友好的:

 不要重復(fù)閱讀者已經(jīng)知道的內(nèi)容

  能明確說明代碼是做什么的注釋對我們是沒有幫助的。

// If the color is red, turn it green
if (color.is_red()) {
  color.turn_green();
}

 要注釋說明推理和歷史

  如果代碼中的業(yè)務(wù)邏輯以后可能需要更新或更改,那就應(yīng)該留下注釋:)

/* 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++) {
  ...
}

 同一行的注釋不要寫得很長

  沒什么比拖動水平滾動條來閱讀注釋更令開發(fā)人員發(fā)指的了。事實上,大多數(shù)開發(fā)人員都會選擇忽略這類注釋,因為讀起來真的很不方便。

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個字符那可以放在代碼旁邊。否則,就應(yīng)該直接把注釋放到語句上面。

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;
    }
  };
}

 不要為了注釋而添加不必要的注釋

  畫蛇添足的注釋會造成混亂。也許在學(xué)校里老師教你要給所有語句添加注釋,這會幫助開發(fā)人員更好地理解。但這是錯的。誰要這么說,那你就立馬上給他個兩大耳刮子。代碼應(yīng)該保持干凈簡潔,這是毋庸置疑的。如果你的代碼需要逐行解釋說明,那么你最需要做的是重構(gòu)。

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可以為你檢查拼寫。如果沒有這個功能,那就去下載插件,自己動手!

 要多多練習(xí)

  熟能生巧。試著寫一些有用的注釋,可以問問其他開發(fā)人員你的注釋是否有用。隨著時間的推移,你會慢慢懂得怎樣才算是友好的注釋。

 要審查別人的注釋

  在代碼審查時,我們往往會忽略查看注釋。不要怕要求更多的注釋,你應(yīng)該提出質(zhì)疑。如果每個人都養(yǎng)成寫好注釋的好習(xí)慣,那么世界將會更美好。

 總結(jié)

  注釋是開發(fā)進(jìn)程中非常重要的一部分,但我們不應(yīng)該為了注釋而注釋。注釋應(yīng)該是有用的,簡潔的,應(yīng)該是對代碼的一種補(bǔ)充。注釋不應(yīng)該用于逐行地解釋代碼,相反,它應(yīng)該用于解釋業(yè)務(wù)邏輯,推理以及對將來的啟示。

  英文原文:Do’s and Don’ts of Code Comments 翻譯:codeceo

標(biāo)簽: 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:6 個簡單的bug追蹤技巧!

下一篇:最新Android & iOS設(shè)計尺寸規(guī)范