Tuesday, December 15, 2009

Self Documenting Fallacy

I've been doing a fair amount of coding these last few days, both at work and at home, and the one thing that kept floating through my head was the idea of self documenting code.

According to this theory comments, that is non-compiled language, should not be needed because the code itself should tell any developer what the code does.

As a childish example we have this snippet of code:

System.Out.Println("Hello World");

This is the first line of code most programmers write in a new language, all it does it print the words "Hello World" to the screen. Now, let's add a comment:

//Prints Hello World
System.Out.Println("Hello World");

In this context the idea of commenting seems absurd. It's one line of code and the comment shares many of the same words as the line of code it's documenting.

However most sections of code are not one line, and they certainly are not as trivial as a print statement. yet the belief persists that if you write good clean code then comments are not only unnecessary, they are actually counterproductive as they clutter the code and make it less readable.


I have a hard time remembering what I had for breakfast, if I even ate breakfast, let alone what I was doing with a piece of code six months ago. Comments, when used judiciously to document tasks left undone, or pieces of code that need work, or methods that have some special behavior simply make sense.

I don't advocate commenting every line of code, nor do I advocate not commenting at all, but I do feel they have their place and should be used in a professional environment. However, that's a stance that seems to be all too uncommon these days.

No comments: