Monday, June 27, 2011

Commenting: The Lazy Way Out

I'm a big believer in self documenting code. That is, code that is structured to be readable without comments. There are a lot of problems with comments. First, they are notorious for getting out of date. If you've ever been bitten by a misleading comment, you will know that no comment is much better than a false one. I see most comments as crutches. You have this bad code, and you try to "fix" it by just adding comments to the code, since that's the easiest way to make the whole package somehow understandable. Unfortunately, at the end of the day, the code is still awful. In this way, comments are the lazy way to make code readable. In fact, most of the time I treat comments as a potential code smell. It is almost always better to refactor the code to be more clear, instead of annotating the code.

I've heard other developers say things like self-documenting code is a lazy excuse for not adding comments. I disagree. Writing self-documenting code is orders of magnitudes harder than writing descriptive comments. It also requires a lot more time and effort than just commenting your code. However, it is also much more effective at making code readable. When your code only makes sense in the presence of comments, you are making that code much harder to use in other areas. Are you going to include the comments wherever the bad code is used? Copy-pasta?

There are, however, a few cases where comments are the way to go. They are much easier and quicker to write than actually refactoring the code. This makes them preferable when you have to write code under a very tight deadline. However, I would treat them like any other "hack" developers do in the heat of a release; do it now, and fix it as soon as possible when the deadlines loosen up.

There are also some times where refactoring the code will lead to a lot more code for little readability benefit. In these cases, a comment might be a better solution. Having too much code, however clean, is also a very big problem, because it makes the overall project harder to understand. However, to me this seems like a rare case. It is almost always better to refactor than to add a comment.

As an exercise, take a look at some old code you wrote and find the lines of code with comments. Can you think of a way to refactor it to be cleaner? I think in 90% of those cases, you will be able to refactor the code to make it much more readable without comments.

No comments:

Post a Comment