Proper commenting

I saw a link to this page from Digg, listing 10 pieces of programming advice that should not be followed. One of them regards commenting (emphasis mine):

6) “Write lots of comments”
Make sure you comment your code. Otherwise, it will be impossible for anyone to understand – including yourself in a year or so. I have heard that many many times and thought that it was probably right. It makes sense after all, and I have often found use of comments when trying to find meaning in somebody elses code. Particularly, I have struggled with comment-less code and sworn that I would never make that mistake. However, this is mostly the case when the code is not self explanatory. Which it should be. If you feel the need to write comments in your code, I suggest you try to refactor instead, so comments won’t be needed. Renaming some variables or introducing a function call will probably do the trick. Context is better documented using assertions. In fact, a context that cannot be described using assertions is probably a bad sign!
There are times when comments serve a pupose though. Algorithmics can be hard to grasp and yet impossible to simplify through further abstractions. In such cases, you can explain yourself with comments. I think my colleague Lars Thorup pointed out a very good test for comments: they should contain the word “because”. This way, you know that you are answering a why rather than a what.
Oh, and my favourite specialization of the comments advice: keep a history of changes and author info etc. in the top of each file.
I’ve never actually heard anyone say that you should do this but I have seen it so many times that there must be people out there recommending it. Why on earth you would clutter the code with information that so obviously belongs in the version control system is just beyond me.

I think the key point here is that comments should explain “why” and not “what”. I don’t think I ever quantified what good comments were until now, but this makes lots of sense. Some “what” comments are good at the functional level for instance, because they summarize blocks of code, but most line-level comments should be explaining the “why.” If you have to explain to me what you’re doing in a line of code, then something tells me your code is pretty bad.

This is bad:

// Clears the frizzle of the froider

This is good (sort of):

// Ensure ISO-900000 compliance by keeping our froiders clear

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *