OK, I used that entry title to get your attention. What it really should say is "Before you add a comment to your code, stop and ask yourself why you think you need a comment here." Clint Willard has an interesting blog entry today on code comments, and I wanted to expand a bit on what he had to say. I agree with Clint that comments are mostly unnecessary in a clearly coded application.
In the vast majority of cases, a comment indicates that something is wrong. If you have to add a comment to explain what a block of code is doing, that means that the code is too complicated or is using poor variable names or function calls.
Consider this code:
<cfoutput> <!--- Replace the dots with slashes, then replace the root mapping name with the absolute path from the web root to the application. ---> #ReplaceNoCase(ListChangeDelims('sitemapping.components.services', '/', '.'), 'sitemapping/', '/mysite/')#/ </cfoutput>
Without the comment, someone looking at this code would probably be rather confused, or at least require them to take the time to read over it several times to dissect it and figure out what it is doing. The comment helps to explain what the code does. But this is still an undesirable outcome. In cases like this, one should consider moving the code into its own method and using good naming to convey what the code does. Something like:
<cffunction name="convertPackageToPath" access="public" returntype="string" output="false" hint="I convert a package name into an absolute path from the web root."> <cfargument name="package" type="string" required="true" /> <cfset var path = ListChangeDelims(arguments.package, '/', '.') /> <cfset path = ReplaceNoCase(path, 'sitemapping/', '/mysite/') /> <cfreturn '#path#/' /> </cffunction> <cfoutput> #convertPackageToPath('sitemapping.components.services')# </cfoutput>
Now we have much more self-documenting code. Someone coming to this line of code can understand what is going on immediately. And if we spend a little more time to make the values in the method more dynamic, such as the mapping name or the site root, we gain even more benefit. The method becomes a nice, generic option for a wide range of use cases where we want to convert package names into web-root-relative paths.
That said, of course comments have their place. They can be a good place to explain why something is happening. And they are fine for header information, documentation, or TODO entries that will be picked up by the IDE and added to your task list. But the main point is that self-documenting code should be the goal. So the next time you write or run into code that you think needs comments to explain it, consider refactoring to remove the complexity and make life a bit easier for yourself and anyone looking at the code in the future.