注释不能美化糟糕的代码 Comments Do Not Make Up for Bad Code
注释是用代码表达意图遭遇的失败
写注释的常见动机之一是糟糕的代码的存在
用代码来阐释 Explain Yourself in Code
清晰的代码本身就能有效表达意图,应避免依赖注释
确实存在代码难以解释逻辑的情况。不幸的是,许多程序员因此认为代码几乎无法成为好的解释手段,这是错误的观点。如
1 | // check to see if the employee is eligible for full benefits |
可以重构为:
1 | if (employee.IsEligibleForFullBenefits()) |
很多时候,简单到只需要创建一个描述了与注释所言同一事物的函数即可。
好注释 Good Comments
法律信息 Legal Comments
提供信息的注释 Informative Comments
对意图的解释 Explanation of Intent
阐释 Clarification
警示 Warning of Consequences
TODO 注释 TODO Comments
放大 Amplification
公共 API 中的 Javadoc Javadocs in Public APIs
坏注释 Bad Comments
喃喃自语 Mumbling
多余的注释 Redundant Comments
误导性注释 Misleading Comments
循规式注释 Mandated Comments
日志式注释 Journal Comments
废话注释 Noise Comments
可怕的废话 Scary Noise
能用函数或变量就不用注释 Do not Use a Comment When You Can Use a Function or a Variable
位置标记 Position Markers
括号后的注释 Closing Brace Comments
归属与署名 Attributions and Bylines
注释掉的代码 Commented-Out Code 删掉而不是注释
HTML注释 HTML Comments
非本地信息 Nonlocal Information
信息过多 Too Much Information
不明显的联系 Inobvious Connection
函数头 Function Headers
非公共代码中的 Javadoc Javadocs in Nonpublic Code