June 26, 2006

Programming in the small - comments.

Following on from the previous article in the series, another "programming in the small" thing that I look out for is comments.

I've been indecisive about publishing this article because it seems so obvious; but I know from seeing code at dozens of different clients over the years that somehow it isn't. I think it's another example of a cargo cult.

Pointless comments

A comment on a method "getName" that says "returns the name" doesn't tell you much. I've seen many such comments; usually the result of a project standard whereby all methods have to have a comment. You may think that such a comment is harmless - but it isn't because it takes time to write, time to read and makes the source longer without adding anything.

Misleading comments

Even worse than pointless comments are misleading ones. I think it was Weinberg in The Psychology of computer programming who made an observation that when debugging, misleading comments can make it take longer to work out what's happening than if you delete all the comments. Misleading comments can lead you into a truth trap.

Useful comments that shouldn't exist

Sometimes comments can be useful; for example telling you that some lines of code together mean something, for example "estimated journey time". However, it would be better to extract those lines of code into a method called, for example, "estimatedJourneyTime". Often comments can be an indication that the names of a variable should be improved, or a method extracted.

Beck on comments

Kent Beck wrote about comments in Smalltalk best practice patterns - worth reading whether you use Smalltalk or not. I was so pleased to read what he wrote about comments - he expressed clearly what I felt at the time with the code I was working with then.

Not all comments are bad

Sometimes comments are good.

Education, education, education

I think the over-use of comments (and "structured programming") comes from University computer science courses, so maybe I shouldn't be suprised by the prevalence of a belief that comments are good (and many developers, or their bosses, feel they "should" be writing more comments).

Blog Comments

From Malte Finsterwalder:

Hi Ivan,

I always remember a quote from the book "Code Complete" : "Don't comment
tricky code - rewrite it!"

Also an interesting observation: Heavily documented code contains more
errors!

Greetings,
Malte

Posted by ivan at June 26, 2006 9:37 PM
Copyright (c) 2004-2007 Ivan Moore