I recently came across a post on elegantcode.com that really struck a nerve. The premise: If you write good code, comments should not only be unnecessary, they could actually be counterproductive. Says author John Sonmez:
“As my experience has increased, I have realized more and more that comments are actually bad. They indicate a failure.”
I know that this runs contrary to what most professors, instructors and textbooks say. They offer what seems a reasonable rule: Comment your code so that the next person who reads it doesn’t need to try to figure out what you’re doing.
And it’s also contrary to most of the code I put out on this Web site. I would certainly agree that I over-comment my code, but that’s a conscious decision, based in large part because I want my readers, who tend to be newer programmers, to completely understand what my code is doing at each step.
But as Sonmez notes, comments aren’t the best way to achieve that goal, especially in object-oriented code.
For example, if you change code, its related comment doesn’t change. Use proper constants — e.g., DEFAULT_LOOP_ITERATIONS — instead of a variable declarations. Name your methods, properties and function so they are self-documenting (do you really need to comment a method named OpenXMLFile?) and write more code so that self-documenting names can replace more abstract procedural code calls.
It’s this third suggestion that interests me. I’ve said, many times, that less code is better. I maintain that view. But I’m inclined to agree more with Sonmez that, if it takes a few extra lines and a couple more dependencies to create self-documenting code, that complexity is probably the right trade-off, versus adding novella-sized comment blocks.
I’m almost certainly going to continue over-commenting code here, especially because I am trying to serve the needs of novice programmers.
But Sonmez’s brilliant post really hits hard, and reminds me that if I am trying to write simple code that’s easy to understand, I should rely more on best programming practices than double-slashes. Expect to see more of that in the future. And please do take the time to read his post in full.
All links in this post on delicious: http://delicious.com/dougvdotcom/good-coding-practices-should-replace-comments-in-code