- Use comments to justify code, not to describe how it works. We can read code, but why it is there at all is often a mystery.
- Most programmers have lousy short-term memories. Keep the comments close to the code they justify.
- Use comments to explain idioms that might not be obvious to junior programmers. E.g.:
// enforce precondition: a to be between 0 and 59
a = (a<0) ? 0 : ((a>59) ? 59 : a);
- Use lengthy comments to explain what you've done when you've done something fiendishly clever--particularly in assembler, C or other cryptic language. Explain it to your baby sister. I have one chunk of code in my Forth interpreter that has most of a page of comments to explain ten lines of code that make really odd use of poorly documented 80x86 internals. It was weird enough that ten years later I have a problem understanding the comments, to say nothing of the code.
- Write Sweet-Smelling Comments:
http://www.stickyminds.com/testing.asp?Function=edetail&ObjectType=ART&ObjectId=9041&tth=DYN&tt=siteemail&iDyn=3
MichaelFeathers notes in the article, for example, "Long methods are easy to spot because they typically have a common form: a series of comments describing the purpose of a block of code that follows each comment." A decent heuristic is that when there is comment on a block in a long method, that block is a shorter method trying to get out, and often the comment is a guide to a good IntentionRevealingMethodName
?