File Under: Programming

Commenting Your Code — What’s Too Much, Too Little?

HeadtattooDo you often forget to comment your code and find yourself scratching your head years later, trying to figure out what’s going on? After a few experiences like that you might be tempted to start leaving comments all over the place, but that can be just as bad of an idea.

Blogger Jeff Atwood recently posted an interesting look at what makes good comments and how some simple refactoring can make your code self-documenting. If you stick to best practices like giving functions and variables logical names, it shouldn’t be too hard for you or others to figure out how your code works.

That helps eliminates the need to strew comments throughout your code. All that remains to comment is a quick explanation of why your code works.

As Atwood writes, “I’m constantly running across comments from developers who don’t seem to understand that the code already tells us how it works; we need the comments to tell us why it works.”

Atwood walks through a couple of examples of how refactoring some totally uncommented code makes it infinitely more readable and doesn’t add extraneous comments.

So where’s the balance? What’s constitutes over-commented code and what is under-commented? Atwood compares it to writing a book:

Junior developers rely on comments to tell the story when they should be relying on the code to tell the story. Comments are narrative asides; important in their own way, but in no way meant to replace plot, characterization, and setting.

I encourage you to have a thorough read through the article since there’s a lot of good practical advice in it (and a hilarious example of some ridiculously over-commented code). In the end, how many comments your code contains is up to you, but remember the more self-documenting your code is the more readable it becomes.

[photo via MethodShop on Flickr]

See Also: