Simple Rules on Commenting Code

Posted on March 11, 2011

0


CC-by-SA

Note: This post has been rendered obsolete by a new version of it here.

 

I’ve seen questions about comments every once in a while, and I found this recent one in SO very interesting. What tense should we use when writing comments?

The question is very simple (simple enough for many l33t hax0rs to dismiss it), but it does raise a question on how to write good comments (an art on itself.) For me, I tend to follow some rules of thumb that I’ve derived throughout the years.

To me, comments are (or should be), like anything written, expressions of something, and they should simply follow the same rules in natural languages (taking into account shorthands and abbreviations specific to the situation or artifact being documented.

Comments in the present tense (.ie “it changes” or “it is changing”) indicates that a piece of data being operated by the documented algorithm is being affected somehow. That is, it explains either what the code is doing or what is occurring to the the data being manipulated.

Comments in the past tense should indicate an assertion, precondition or post-condition of something that has happened prior to the point where the comment resides. For example:

Input has already been validated before entering this block of code

or

Data has been written to file at the end of this code being executed

Comments in the past tense can also explain why something is being done (this function does X and Y to deal with a problem with the legacy database.)

Comments in the past tense indicating a change to the code itself (.ie. X was changed to Y) should not exist in the code. They should instead exist as revision comments in the source code repository.

Comments in the future tense should indicate a condition that needs to be met or addressed, but that for X or Y reason is not being done right now. For example:

When we finally migrate the db, we will have to change this logic

or

TODO: asap, revisit validation of input – it might fail for X or Y type of input, might require massive changes that cannot be implemented right now.

For the later TODO type of comments, some other form of documentation should exist to make sure that such changes actually take place. The last thing you want are TODOs lost in time and space 😛

Take it with a grain of salt, but typically those are the rules I usually follow when I do my own comments. I hope you find them useful.

CC-by-SA