健康的代码:什么时候该注释?

125 阅读1分钟

健康的代码:什么时候该注释?

在阅读代码时,没有什么比正确的注释更有帮助了。然而,并不是所有的注释都是有用的。有时候,需要注释可能表明应该重构代码了。。

如果我们不能使写出的代码不言而喻,那默认就是注释上场的时候了,可以首先尝试以下一种方法:

  1. 多用一个变量解释用意

bad:

// 从价格中减去折扣
const finalPrice = (numItems * itemPrice) - (numItems * itemPrice * 0.1);

good:

const price = numItems * itemPrice;
const discount = numItems * itemPrice * 0.1;
const finalPrice = price - discount;
  1. 提取方法

bad:

// 过滤敏感词
for (const word of words) { ... }

good:

function filterOffensiveWords(words) { ... };
  1. 使用更具有描述性的变量名称

bad:

const width = ...; // 像素宽度

good:

const widthInPixels = ...;
  1. 如果代码有假设,最好添加一个检查

bad:

// height肯定大于0
return width / height;

good:

assert(height > 0);
return width / height;

在某些情况下,注释可能会有所帮助:

  1. 说明意图:解释为什么要这么写(而不是常规操作)
// 仅计算一次,因为它很耗性能
if (computed) return
  1. 防止将来善意的同事错误地“修复”了代码
// 必须创建新的Foo实例,因为单例Foo是不安全的
return new Foo()
  1. 说明在code review的时候出现的问题或源码阅读者可能遇到的问题
// 请注意,顺序很重要,因为...
wash()
brush()
  1. 解释使用看似不正确做法的理由
(name as number).toFixed() // name是number类型,是因为...

另一方面,避免只重复代码功能的注释,这些只是画蛇添足

// 获取所有用户
userService.getAllUsers();
// 检查名字是否为空
if (isEmpty(name)) { ... }

原文:testing.googleblog.com/2017/07/cod…