Saturday, May 10, 2008

About comments

Once more, I found a questionable code comment of the irritating variety. Basically, I ran into a method like this.

    "The code should do this"
    self butTheCodeTurnsAroundAndDoesSomethingElse.

Now that is helpful... so I just fixed it by deleting the comment and having the code do what the comment was suggesting, which was the appropriate thing to do in the first place.

However, imagine for a moment that you do not look at the code and just look at the comments --- such as when you look at some API documentation for which you are not given the actual implementation. So you read "the code should do this", and then you get the idea that it really does. Wrong!

If you do not have the code to check, well that is unfortunate and it has to be dealt with. But what if you do have the source code? Wouldn't you look at it? After all, what if the comment is wrong? Or what if the code has a bug?

This is where comments start losing their appeal to me. We developers are supposed to be well trained in reading code. What is this business of choosing not to look at code but instead looking at some commentary that may or may not be an accurate description of what the code is doing? And, if after you read the comments, you go look at the code anyway... what was the benefit of reading the comments?

Seriously: if you have available source code, and nothing is funny about it (e.g.: choice of magic constants), why look at comments at all? Or, more strongly perhaps: why would developers, of all people, choose not to look at code?

So... if programmers avoid reading code, then who is supposed to do the actual programming instead?


Regina said...

I tend to agree with you for the most part. One reason I find to comment is when you are doing something perverse (or questionable in your code) and then comment details why you are taking this non-orthodox route - so you don't come back 5 weeks later and wonder why you did something a certain way.

Andres said...

Right... barring something like the choice of magic constants or something really obscure, I think Roger Whitney sums it up rather nicely:

"Don't comment bad code --- make the code better!"