# Monday, February 16, 2009

How about those code comments?

I just read Daniel's post on 'The Value of Commenting'. Food for thought people :-)

I like to use the following rules of thumb:

a) Code should be self explanatory. This means using well named variables, properties and objects in order to make code as easy to read as possible. It should be obvious from the code what it is that it is trying to do.

b) Code should be easy to read. By easy I mean that you need to be able to scan it pretty fast. Sometimes comments can help make code easier to read by describing what is going on. I find this especially true in if/else constructions where a short comment can guide the reader of the code.

c) If more that one line of code is needed to describe a code block, consider refactoring the code to a private method and put comments on the method. A useful name for the method should help in achieving point (a).

d) Comments should describe why you're trying to do something, but this has limits. Extensive explanations on why the purchase amount of an order should never exceed $10000 should not be in the code. A list of rules should be maintained as part of the documentation and a reference to the rule should be made from the code comments.
Note: I have been known to document a list of rules as an enumerator, where the documentation of the rule is documented as the description of the enumerated value.

Actually (d) is the hardest one. When is it necessary to describe the 'why' of an operation?
The code is readable, the original programmer put it there for a reason. Are the comments there because the presence of the code needs to be justified? No! The 'why' comments are to facilitate (b).

As always, it's easy to spot useless comments, but hard describe a fixed set of rules to describe good comments. Use your brain!

#    Comments [2] |
Monday, February 16, 2009 10:33:31 AM (Eastern Standard Time, UTC-05:00)
I agree with your points 100%. I also agree with the ordering of those points. Comments are certainly valuable, and in some cases almost critical. On the other hand, if given the choice between well-structured code and well-commented code, I'll choose the first.
Monday, February 16, 2009 1:58:39 PM (Eastern Standard Time, UTC-05:00)
They say that if your comments and your code don't agree... both are wrong.

So be sure to keep the comments updated to match the code. And for the record, I follow a lot of the same comment guidelines myself. :)
Comments are closed.