Use a comment when it is infeasible to make your code self-explanatory.
當你的代碼不容易自我解釋邏輯的時候,才需要寫注釋。
如果你發現自己的代碼可以自我解釋邏輯,則不需要添加注釋。
例如下面代碼中的注釋都是沒有意義的:
// Get all users.
userService.getAllUsers();
// Check if the name is empty.
if (name.isEmpty()) { ... }
如果你發現自己的代碼不容易自我解釋邏輯,首先可以嘗試修改代碼,讓它變得容易自我解釋邏輯。
示例
例如下面這樣一段計算最終價格的代碼:
finalPrice = (numOfItems * itemPrice) - max(20, numOfItems) * 0.1;
其他人并不懂 max(20, numOfItems) * 0.1
是什么意思,因此你第一想法肯定是加上注釋,例如:
// Subtract discount from price.
finalPrice = (numOfItems * itemPrice) - max(20, numOfItems) * 0.1;
其實更好的辦法是引入一個可以自我解釋的變量,例如:(這樣其他人一眼也能看懂)
price = numOfItems * itemPrice;
discount = max(20, numOfItems) * 0.1;
finalPrice = price -- discount;
示例
例如下面這樣一段過濾字符串數組的代碼:
for (String word : words) { ... }
其他人并不懂這一段的目的是什么,因此你第一想法肯定是加上注釋,例如:
// Filter offensive words.
for (String word : words) { ... }
其實更好的辦法是引入一個可以自我解釋的方法名,例如:(這樣其他人一眼也能看懂)
filterOffensiveWords(words);
String[] filterOffensiveWords(String[] words) {
for (String word : words) { ... }
}
示例
使用更有意義的變量名,例如:
int width = ...; // Width in pixels.
我們可以使用 int widthInPixels = ...;
來取代注釋。