代碼注釋中的5要與3不要
代碼注釋?zhuān)梢哉f(shuō)是比代碼本身更重要。這里有一些方法可以確保你寫(xiě)在代碼中的注釋是友好的:
不要重復(fù)閱讀者已經(jīng)知道的內(nèi)容
能明確說(shuō)明代碼是做什么的注釋對(duì)我們是沒(méi)有幫助的。
- // If the color is red, turn it green
- if (color.is_red()) {
- color.turn_green();
- }
要注釋說(shuō)明推理和歷史
如果代碼中的業(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++) {
- ...
- }
同一行的注釋不要寫(xiě)得很長(zhǎng)
沒(méi)什么比拖動(dòng)水平滾動(dòng)條來(lái)閱讀注釋更令開(kāi)發(fā)人員發(fā)指的了。事實(shí)上,大多數(shù)開(kāi)發(fā)人員都會(huì)選擇忽略這類(lèi)注釋?zhuān)驗(yàn)樽x起來(lái)真的很不方便。
- 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
- }
要把長(zhǎng)注釋放在邏輯上面,短注釋放在后面
注釋如果不超過(guò)120個(gè)字符那可以放在代碼旁邊。否則,就應(yīng)該直接把注釋放到語(yǔ)句上面。
- 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à)蛇添足的注釋會(huì)造成混亂。也許在學(xué)校里老師教你要給所有語(yǔ)句添加注釋?zhuān)@會(huì)幫助開(kāi)發(fā)人員更好地理解。但這是錯(cuò)的。誰(shuí)要這么說(shuō),那你就立馬上給他個(gè)兩大耳刮子。代碼應(yīng)該保持干凈簡(jiǎn)潔,這是毋庸置疑的。如果你的代碼需要逐行解釋說(shuō)明,那么你最需要做的是重構(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
- }
注釋要拼寫(xiě)正確
不要為代碼注釋中的拼寫(xiě)錯(cuò)誤找借口。IDE可以為你檢查拼寫(xiě)。如果沒(méi)有這個(gè)功能,那就去下載插件,自己動(dòng)手!
要多多練習(xí)
熟能生巧。試著寫(xiě)一些有用的注釋?zhuān)梢詥?wèn)問(wèn)其他開(kāi)發(fā)人員你的注釋是否有用。隨著時(shí)間的推移,你會(huì)慢慢懂得怎樣才算是友好的注釋。
要審查別人的注釋
在代碼審查時(shí),我們往往會(huì)忽略查看注釋。不要怕要求更多的注釋?zhuān)銘?yīng)該提出質(zhì)疑。如果每個(gè)人都養(yǎng)成寫(xiě)好注釋的好習(xí)慣,那么世界將會(huì)更美好。
總結(jié)
注釋是開(kāi)發(fā)進(jìn)程中非常重要的一部分,但我們不應(yīng)該為了注釋而注釋。注釋?xiě)?yīng)該是有用的,簡(jiǎn)潔的,應(yīng)該是對(duì)代碼的一種補(bǔ)充。注釋不應(yīng)該用于逐行地解釋代碼,相反,它應(yīng)該用于解釋業(yè)務(wù)邏輯,推理以及對(duì)將來(lái)的啟示。























