Comments on Comments on Comments
Intent comments, as Gunderloy explains, provide the answer to "why?" I find myself needing these sorts of most frequently. "This hard-coded implementation of ln provides optimal performance against a specific range of data."
Some intent comments can be supplanted with unit tests. I practice test-driven development (TDD), and as such, I seek to craft my unit tests so they too are highly readable. Done well, TDD can produce test methods that read as examples of how to use a class. Done better, these examples can start to act as a form of specification. When interacting with a well-written TDD system, I use the tests as my first understanding of the code. They help me navigate and understand the capabilities of each of its classes.
Comments do not come without a cost. They take time to enter. Comments must be maintained in synch with the code. Often, they are not maintained, in which case they become useless at best, misleading at worst. They also can detract from the readability of code if they are excessive or redundant.
How do I really know if my code needs a comment? A pair generally knows the right answer. Pairing helps dramatically by ensuring that the code needs fewer comments through refactoring. In lieu of a pair, another great technique I've employed is to have someone spend a minute or two trying to paraphrase my code (test code too).
I no longer seek to defend comments. Instead, I view most comments as opportunities to improve upon the code and tests. Certainly, there will always be the rare exception, the complex code that cries out for a comment. But that's not an excuse to not try to first clean up the code. I look at every method with a critical eye, and try to find a way to make it shorter or clearer through elimination of comments. If it's still unclear, only then do I add a comment.
Maintenance is indeed costly, and creating maintainable code is an art. Adding a comment is too often an indicator that I'm failing at ensuring the code supports future comprehension. I now reflect each time I feel compelled to add a comment, to see if perhaps there's a better way. Sometimes, there is; sometimes, there is not.
|To join in on a discussion on comments within code go to the CodeGuru discussion forum: General Discussion > General Developer Topics http://www.codeguru.com/forum/showthread.php?t=415553.|
About the AuthorJeff Langr is a veteran software developer with a score and more years of experience. He's authored two books and dozens of published articles on software development, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him directly at firstname.lastname@example.org.
Page 2 of 2