Friday, 7 January 2011

To comment or not to comment

I was just following an interesting thread in Slashdot about commenting code. You can take a look if you want: Myths About Code Comments.

I think that the controversy about this subject comes mainly from people who are not developers and, therefore, cannot possibly have a clear opinion about it. Of course, if I am a manager buying a product with source code, I will make sure that everything is well documented before I pay for it. However, software is not like an object that you buy with a user guide that will always be relevant because the object will never change until it falls apart. With software, things are quite different: in general, if one has the source code there will be changes applied to it.

The big trap of extensively commenting code is that there is no guarantee that someone will update it to reflect the changes brought to the software afterwards. Then we will have the worse situation where the documentation does not correctly describe the code. It is worse because it could be misleading and cost you a lot of hours pointing to the wrong direction when you're trying to solve a bug.

As a developer I always stayed away from documentation of code that has been through several cycles of modifications, much preferring to concentrate on the code itself and trying to understand it as much as possible. Because of that, I tend to agree with those who preach that code should primarily be self-documented.

Once upon a time I was called to program some expansions to a Unix device driver for TTY terminals. The code was voluminous and I could not see much documentation around it. To make things worse, I had just started programming in C... Nevertheless, I was able to successfully perform the task in the allocated time and this I owed exclusively to the developer who not only wrote excellent self-documented code but was also very tidy in formatting all the source lines, making the code very easy to follow.

To cut a long story short, I would say that if the customer demands documentation, you should do it in the way that pleases him, mainly because I assume you are doing developing for a living. However, always take into consideration your fellow developers: write clear, well-formatted and self-documented code, avoid complexity and embrace simplicity, and drop a useful comment here and there where it is really needed. Above all, use separate lines for those comments, never put them in-line with the code, they will disappear indiscriminately when changes are made...

No comments:

Post a Comment