美文网首页
什么是好的代码注释?

什么是好的代码注释?

作者: 专职跑龙套 | 来源:发表于2019-04-05 16:48 被阅读0次

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 = ...; 来取代注释。

...持续更新...

相关文章

网友评论

      本文标题:什么是好的代码注释?

      本文链接:https://www.haomeiwen.com/subject/acckiqtx.html