On Code Comment

来源:互联网 发布:矢量数据的编码方式 编辑:程序博客网 时间:2024/05/01 01:44

Brian W. Kernighan and Rob Pike have some excellent suggestions for writing comments. They are said best as they appear in "The Practice of Programming," [1]:

  • Don't belabor the obvious. Comments shouldn't report self-evident information such as the fact that i++ has incremented i.

     

  • Don't comment bad code, rewrite it. Comment anything unusual or potentially confusing, but when the comment outweighs the code, the code probably needs fixing.

     

  • Don't contradict the code. Most comments agree with the code when they are written, but as bugs are fixed and the program evolves, the comments are often left in their original form, resulting in disagreement with the code. Whatever the source of disagreement, a comment that contradicts the code is confusing, and many a debugging session has been needlessly protracted because a mistaken comment was taken as truth. When you change code, make sure that the comments are still accurate. Comments should not only agree with code, they should support it.

     

  • Clarify, don't confuse. Comments are supposed to help readers over the hard parts, not create more obstacles.

     

  • When it takes more than a few words to explain what's happening, it's often an indication that code should be rewritten.

     

  • Students are taught that it's important to comment everything. Professional programmers are often required to comment all their code. But the purpose of commenting can be lost in blindly following rules. Comments are meant to help a reader understand parts of the program that are not readily understood from the code itself. As much as possible, write code that is easy to understand; the better you do this, the fewer comments you need. Good code needs fewer comments than bad code.

References

[1] Kernighan, Brian W. and Pike, Rob, The Practice of Programming, Addison Wesley, 1999, pages 23-27.