If it’s important enough to comment, it’s important enough to test

Several people disagreed when I said you should try to write code that doesn’t need comments. I’ll be addressing some of their thoughts — sometimes by saying they were right, but sometimes with constructive suggestions.

I’ll start with a couple of people who suggested that comments should try to explain code that was put in to fix a bug, or to explain the “tricky code” that you sometimes have to write.

Those are both scenarios where a comment isn’t enough. You need an automated test.

Tricky code

The best way to deal with tricky code is by not writing it. But I’ll assume you’re dealing with a case where some manner of tricky code is indeed the best way to get the job done.

Suppose you’re writing a Delphi constructor, and for some reason you need to put some code before the call to inherited Create. (That certainly qualifies as tricky.) Assuming there’s a reason why that’s necessary (and not just sloppiness), you should have an automated test that proves the resulting behavior is correct… something that will pass with the tricky code, and will fail without it. A test that would break if someone else (or you, for that matter) later misunderstood the importance of that ordering, and “fixed” it by moving the code after inherited Create. A test that would pass if someone found a less tricky way to accomplish the same thing.

Bug fixes

If you’re fixing a bug, you should definitely be writing an automated test, if at all possible. That way, if someone later makes a change that breaks the same thing again, you’ll know. As Brian Marick said (and we had posted on our wall for a while), “No bug should be hard to find the second time.”

Then look again

Once you’ve got your automated test, take another look. Is the comment still necessary?

Depending on your audience, maybe it is. As someone else pointed out, if you’re a library vendor, then comments have a lot of value.

But I often find that, with the test in place, the comment can just go away.

Making comments less necessary

Compas Pascal posted about how to comment source code. I would argue that good comments are a poor goal.

Comments go stale. This is tough to avoid. When the code gets changed, the comments don’t necessarily follow. The more comments you put in, the faster they get out of sync with what the code actually does.

There are times when comments are necessary; there are things they’re useful for. But whenever possible, you’re better off writing code that doesn’t need comments in the first place.

There are a lot of ways to do this, so I’ll be posting more about it. Meanwhile, what do you think about comments? What do you use comments for? What do you do to write code that doesn’t need comments?