说到注释,总是有争论要不要注释,有人喜欢尽可能多的注释,有人根本不写注释。作者的意见是适当的注释是需要的,但不要重复代码,不好的注释还不如不注释。总结性的,描述意图的注释是好的注释,它会告诉读者代码所没有提供的信息,是我们的目标。而另一大目标就是写出自注释的代码,无比清晰,根本不需要注释。这样可以大大节省读注释的时间,分析注释与代码是否一致的时间,从而提高效率。
具体的方法有很多,
篇幅原因,这里不一一列举了,可以参考下面的checklist去检查。
Checklist: Self-Documenting Code
Classes
- Does the class's interface present a consistent abstraction?
- Is the class well named, and does its name describe its central purpose?
- Does the class's interface make obvious how you should use the class?
- Is the class's interface abstract enough that you don't have to think about how its services are implemented? Can you treat the class as a black box?
Routines
- Does each routine's name describe exactly what the routine does?
- Does each routine perform one well-defined task?
- Have all parts of each routine that would benefit from being put into their own routines been put into their own routines?
- Is each routine's interface obvious and clear?