Comments. Why? Because they tell you why.

hsoi blog, talk Leave a Comment

I’m presently working on a project for a client that involves an old codebase. Some of this code is about 10 years old. Furthermore, the code was acquired so neither I nor my client is the original author.

Consequently, all we can know about the code is what the code tells us.

Alas, the code doesn’t tell me all I need to know. Oh sure, it tells me what it does, but it doesn’t tell me why it does what it does.

This is the reason comments in code are vital. They shouldn’t necessarily tell me what the code does, but they should tell me why the code does.

For example, I encountered a bit of code that checked for the presence of a system file before it could proceed. When testing this code under Yosemite (Mac OS X 10.10, the public beta), the code failed because that file no longer exists. I’m trying to determine if there’s some critical reason for this check, but alas there are no comments in the code nor contact with the original author. So the reason why he did what he did? It is lost to the ether. While I can make some educated guesses about why it’s there and figure out how to proceed, I just cannot be sure if I’m breaking some assumption or critical workaround in doing so. It would have been nice to know why this was done so I could be assured about how to resolve things going forward.

It’s also an important illustration of why such comments need to be in code and not in source control. I’ve known developers that felt the code should be clean and free of such documentation, and instead the explanation should go into the version control in the commit/checkin comment. They also didn’t approve of my habit of prefixing every comment by a time and name stamp:

// Hsoi 2014-07-26 – blah blah

The thing is, the source code will always contain itself and be with itself. There’s no guarantee the version control will be strongly associated with the code. Maybe in the sale or transfer of a project, all they give is the code itself; all that version control history is lost. Who knows. But I know on this project, all I received was the code – no version control. So again, all I had was code, and if perhaps the explanation was in the original author’s version control system, it’s lost to me.

There is an art and balance in commenting code. Always remember that once code is written, it will be maintained and maybe not by you. Or even if by you, will you remember all the details 6 months or 2 years from now? Document why you did what you did, because while the code can tell us things, it can only tell us what you type into it.

Leave a Reply

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