Recently I came across an article suggesting how a good developer should comment their code. This was aimed at those writing SQL scripts, but that doesn't particularly matter. The rules were the same ones I lived by in the 70's and for a long time since then. For example, at the start of each file there should be a modification history, like this:
/* Title: 002 - Setup SQLCMS.sqlPurpose: Setup the various components for SQL CMSVersion: 1.1Modification History:04/30/2009 - Buck Woody - Initial Script Creation05/15/2009 - Buck Woody - Added MAPS load scripts
I copied Buck's since I don't have any like this myself kicking around. And why not? Because VSTS and TFS take care of that for me. Who changed it, what they changed, and why is all available in the repository. Duplicating it in the file itself just gives you another task to forget, and another pair of locations that might get out of sync. So I don't do these any more.
There's another kind of comment that we all used in the 70's and 80's and that was the "explain your names" comment. When you only had 8 characters to work with, you needed a big block of comments that told everyone that NPPLINV was Number of People Invited and CIDMNEW was Calculate Interest, Daily Method, New or whatever. But we don't have name length restrictions any more. So why do I still see this sort of thing:
Dim ClientName as String ' Variable to hold name of clientDim ClientBirthDate as Date ' Variable to hold birth date of clientDim ClientRepID as Integer ' Variable to hold ID of client rep
(Don't believe me? I saw this very code yesterday in a VB6 app I was debugging.)
As Jon Torresdal points out, if you choose your function names and variables well, you don't even need those single lines that explain funky-looking calculations. Extract your weird stuff to a function, even if it's a single-line function, and it explains itself. You can see a similar approach, though comments are never mentioned, in Justin Etheredge's post about isolating logic into little functions.
So let's see, no comments at the top to explain what the file is, no comments after each variable to explain its strange and abbreviated name, no comments before funky calculations because they've been refactored into single line functions ... well what comments even remain, then? Well there's commented-out code - but I have a rule against that. There's this sort of thing:
'only update confirmed date the first time it's confirmedIf DateConfirmed = Nothing OrElse DateConfirmed = New Date() Then DateConfirmed = TodayEnd If
Sometimes these comments are there because the developer wrote the comments first, as pseudo-code, then filled in the code. Other times they are just an attempt to translate the code into English for the reader. Does it help? Well, maybe. But comments are becoming less and less important as time goes by. Interesting.
Click Start a FREE 10-Day trial