Code Commenting Dos and Don’ts
Kids: there is indeed a reason that people tell you to comment your code:
…today I uncovered a long forgotten beloved project of mine, and I dove in to get it into some kind of working shape, now that I had the experience to actually do it right. Of course, there were no comments anywhere, and there were some mysterious things going on, so it took me a while to figure out what it was all about. But this time, every time I figured something out about the old piece of code I put a comment there, explaining what it was all about. By the time I was happily hacking away at it, I realized this was the best documented piece of code I had ever written
This is an excellent way to get your code documented, and I’ve had to do this a few times myself. But imagine if you didn’t write the code in question, and you had to pick up someone else’s project from six months ago? Now the original author’s forgot all about it, and you have to figure everything out on your own.
Commenting your code beforehand saves time, energy, and lives. Leaving it until later is almost a guarantee it won’t get done. But poor commenting can make a file unreadable. Here’s a few good rules:
- Do comment particularly tricky blocks or lines of code. Anything that’s likely to trip up someone reading the code in a few months. If you’re having trouble, check for these problem areas:
- regular expressions
- ternary operations (
x = (expr) ? true : false) - bit twiddling
- global variables
- Do comment variables that aren’t defined in the current scope. PHP with
register_globalson practically demands it. (Or, y’know, just turn it off.) Global variables, or variables that are unexpectedly modified inside subroutines, are also good areas. - Do keep the comments short and to the point. For example, nobody needs an introduction to finite state machines or role-based ACLs in the middle of the code.
- Do update the comments when the code changes. If you’re following the previous rule and keeping things short and succinct this isn’t as much of a chore.
- Don’t comment the obvious. Flooding the file with comments like
# declaring age as an intor// incrementing loop variableactually have the reverse effect and make the code extremely difficult to read. If the code doesn’t need commenting don’t force it.
For the sake of your fellow coders, or your sanity when maintenance time comes, take a few seconds to put a quick # This regex validates a phone number in the format (xxx) xxx-xxxx, with or without the parenthesis.