代碼注釋中的5要與3不要
代碼注釋,可以說是比代碼本身更重要。這里有一些方法可以確保你寫在代碼中的注釋是友好的:
不要重復(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++) {
- ...
- }
同一行的注釋不要寫得很長
沒什么比拖動(dòng)水平滾動(dòng)條來閱讀注釋更令開發(fā)人員發(fā)指的了。事實(shí)上,大多數(shù)開發(fā)人員都會(huì)選擇忽略這類注釋,因?yàn)樽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個(gè)字符那可以放在代碼旁邊。否則,就應(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;
- }
- };
- }
不要為了注釋而添加不必要的注釋
畫蛇添足的注釋會(huì)造成混亂。也許在學(xué)校里老師教你要給所有語句添加注釋,這會(huì)幫助開發(fā)人員更好地理解。但這是錯(cuò)的。誰要這么說,那你就立馬上給他個(gè)兩大耳刮子。代碼應(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
- }
注釋要拼寫正確
不要為代碼注釋中的拼寫錯(cuò)誤找借口。IDE可以為你檢查拼寫。如果沒有這個(gè)功能,那就去下載插件,自己動(dòng)手!
要多多練習(xí)
熟能生巧。試著寫一些有用的注釋,可以問問其他開發(fā)人員你的注釋是否有用。隨著時(shí)間的推移,你會(huì)慢慢懂得怎樣才算是友好的注釋。
要審查別人的注釋
在代碼審查時(shí),我們往往會(huì)忽略查看注釋。不要怕要求更多的注釋,你應(yīng)該提出質(zhì)疑。如果每個(gè)人都養(yǎng)成寫好注釋的好習(xí)慣,那么世界將會(huì)更美好。
總結(jié)
注釋是開發(fā)進(jìn)程中非常重要的一部分,但我們不應(yīng)該為了注釋而注釋。注釋應(yīng)該是有用的,簡潔的,應(yīng)該是對代碼的一種補(bǔ)充。注釋不應(yīng)該用于逐行地解釋代碼,相反,它應(yīng)該用于解釋業(yè)務(wù)邏輯,推理以及對將來的啟示。