Jul 02

It’s easy to disregard writing code comments. Let’s face it, we as coders are not going for the Pulitzer prize, so it’s not about the lack of personal ability of being able to express oneself, it’s just plain laziness.

To be honest, leaving code without descriptive comments where they’re needed is much worse than that. Firstly, it indirectly shows the programmer’s lack of respect towards his peers. Everyone knows how frustrating it is to wade through dozens of classes and even more functions with cryptic, non-self-descripting code, especially when the original coder is on vacation, has left the company or otherwise not unavailable for any other reason. A programmer is an artist, with fellow programmers as the audience. And as all artists, we should learn to respect our audience.

Secondly, leaving out comments shows the programmer’s overconfident attitude towards himself. Sure enough, when writing code, we usually have a good idea of what we’re doing. But programming is often about juggling several things in mind at once, and when you next time look at your code, it may be quite difficult to get back to the mindset you were in when writing the code originally. In these quite common situations, it pays to have descriptive comments in place.

Naturally, I’m not suggesting to comment everything. In fact, one should avoid redundant comments when the code is clear by itself, i.e. when the code is self descriptive. For example, consider the following:

// Declare category id for products
const int prodCategoryId = 1024;

// Create an iterator over products
vector<Product>::iterator iter = products_.begin();

// Iterate through all products
for ( ; iter != products_.end(); ++iter )
{
    // Assign categody id to each product
    iter->AssignCategoryId( prodCategoryId );
}

 
This is an obvious example of excessive commenting. So what to leave out? Consider commenting general ideas, not individual code lines. We can refactor the above comments so that we both reduce comment clutter, yet make our general reasoning obvious:

// Assign categody id to each product
const int prodCategoryId = 1024;
vector<Product>::iterator iter = products_.begin();

for ( ; iter != products_.end(); ++iter )
{
    iter->AssignCategoryId( prodCategoryId );
}

The intent of the code is clear from the single comment alone. What’s more, variable and function names are descriptive enough not to leave too much for the imagination.

Also remember that the more comments you have, the more of a maintenance burden it will be to keep them all up to date. So strive to write concise and descriptive comments only when they are needed.

Leave a Reply

preload preload preload