1. 注释不能美化糟糕的代码
写注释的动机之一是因为代码糟糕,不容易理解。但是不要写长篇大论的注释,去吧代码重写好看些。
带有少量注释的简洁而又表达力的代码,要比带有大量注释而复杂的代码像样的多。
2. 用代码来阐述
简单的创造一个描述与注释所言一样的函数或变量即可。你愿意看到这个:
// Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
还是这个?
if (employee.isEligibleForFullBenefits())
3. 好注释
3.1 法律信息
例如,版权及著作权声明就在每个源文件开头注释处放置的。
3.2 提供信息的注释
// Returns an instance of the Responder being tested. protected abstract Responder resonderInstance();
// formt matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile("\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*");
3.3 警示
警告其它程序员可能出现的某种后果也是有用的。
// Don't run unless you have some time to kill.
public void _testWithReallyBigFile() {
...
}
3.4 TODO注释
IDE可以帮我们收集code中的TODO注释,帮我们追踪没有完成的工作。
3.5 公共API上的注释
public方法是给别人调用的公共API,给其别写良好的注释,它能指导调用者如何使用。
4. 坏注释
4.1 喃喃自语
作者自己了解的注释,他人不明白。
private NameGenerator() {
// Do nothing
}
@Override
protected void checkSubclass () {
// Do nothing
}
4.2 日志式注释
有人会在编辑代码时,在方法开始出添加一条注释,描述自己干了什么。我们有源代码控制系统,可以track谁在做修改,不需要这种注释。
* Changes (from 11-Oct-2001) * ------------------------------------ * 11-Oct-2001 : Re-organised the class and moved it to new package. * 05-Nov-2001 : Added a getDescription() method.
4.3 废话式注释
/**
* Default constructor.
*/
protected AnnualDateRule() {
}
/**
* The day of the month.
*/
private int dayOfMont;
/**
* The name.
*/
private String name;
/**
* Returns the name.
*
* @return name the name.
*/
public String getName() {
return name;
}
/**
* Set the name.
*
* @param name the name to set.
*/
public void setName(String name) {
this.name = name;
}
4.4 归属于署名
源代码控制系统非常善于记住是谁在何时添加了什么。这种署名没必要,而且有时候误导。比如张三添加了类的框架,author是张三,但是代码的大部分实现是李四写的。随着时间的流逝,代码变的越来越和原作者没有关系。
/** * @author Rick */ /* Added by Rick */
4.5 删掉的注释
// InputStream resultsStream = formatter.getResultStream(); // StreamReader reader = new StreamReader(resultsStream);
其他人不敢删除这些注释掉的代码,他们会想,代码依然放在那儿,一定有其原因。时间久了,注释掉改行代码的人都会忘这些注释掉的代码,就像破酒瓶底的渣渣。
不用的代码,尽管删去,版本控制系统可以帮我们再找回来。