Code comments: the best defense need not be offensive

I just wrote a line of code, then added a comment before it.

//these tests don’t bubble up, so…
test.Reset();

Then I thought, “Why am I commenting that? Isn’t the code’s intent explicit enough?” It is quite clear what the code is doing (resetting a test). However, the comment is necessary to give some insight into the business reason for the code.

The comment is useful because the instructions in the code may contradict the expected business logic. If the action (resetting the test) was expected, it would not be necessary to add the comment; that wasn’t the case for me.

This is an example of what I call a defensive comment. It helps avoid the situation where someone looks at code and wonders whether it is logically incorrect. That someone may be another programmer, or it may be yourself, months after you’ve forgotten why you wrote the code in the first place.

Lots of people say that code should be self-commenting. This doesn’t work in all situations. We shouldn’t fear a brief one-line comment to help give our code context and spoken-language meaning. Comments need not be offensive when used defensively.

One thought on “Code comments: the best defense need not be offensive

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.