Myths about code comments

Posted by Fenil Desai | 4:35 AM | , , | View Comments

Myths about code comments

It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development. However, I feel that this is a part of programming that's almost as important as writing code itself. So, here are some of the biggest misconception about comments:

Comments are free

This is an assumption that most of us make at one time or another. Comments aren't actually executable code, therefore they aren't maintenance costs, right? As it turns out, this isn't true. When you update the code that the comment references, you usually have to update the comment as well.

Unfortunately, this myth is actually true most of the time. After enough time staring at a comment, it typically becomes "noise" that you tune out. Thus, comments have a nasty habit of not being up-to-date.

Comments make code more readable

This is by far the most pervasive myth that I've encountered. If anything, comments make code less readable. Nine times out of ten, I ignore comments unless I'm stumped. In fact, I'm tempted to make emacs hide all comments unless I explicitly expand them.

Comments don't make code more readable. They are ways to compensate for code not being readable.

You should comment every function, method, class, and module

How many times have you seen docstrings like this?

 

  1. def get_x(self):
  2. """
  3. This method gets x.
  4. """
 def get_x(self): """ This method gets x. """ 

This is about as close to being a canonical "bad comment" as you can get, and yet people who should know better still do it. Why? Because they feel that they should document every function or class. The reality is that documenting something that needs no documentation is universally a bad idea.

Code must always be "self documenting"

Most of the myths thus far have been of the "comments are a wholesome, healthy thing variety". Don't take this to mean that I feel that comments are bad. The reality of the situation is that the decision of whether to comment is just like most other decisions in programming: it's about tradeoffs.

In most cases, comments should be viewed as code smells. But remember that code smells aren't necessarily bad. They're just hints that something might be bad. And sometimes, removing one code smell adds another one which may or may not be worse.

For instance, would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments? In most cases, code's readability suffers more when it's overly verbose than when it has a high comment to code ratio. Thus, I would choose to write the comment in most cases.

 

Posted via email from fenildesai's posterous

Share Related Posts with Thumbnails
blog comments powered by Disqus