Saturday, February 15, 2014

Commenter's Block

I have been thinking about comments today (the kind that you add to code, not to blogs). Adding comments to code is one of the first things we are taught to do, but I realized that it isn't that simple to do well.

I recently asked a co-worker to review a change I made. He replied,
"Each individual change looks fine, but there's a lot about the code that I don't really understand. Can you add some comments?"

I replied,
"Sure, the code is a bit gnarly and complex. Instead of me guessing what you think is unclear, can you quickly point out what spots need comments?" We use a nice tool for code reviews that makes asking for updates really easy.

He replied,
"You know what, I'll just accept your change for now. It's too hard for me to figure out what really requires a comment and what doesn't. Maybe we should chat about it later."

So, I've checked in the code and started rolling it out, without additional comments, but I wish I had a better idea of what's the BEST practice for adding comments? I don't have a complete guide in my head, but here are some random thoughts on the subject.

/* @author = Me, 
    @name=file.h */
I don't understand these types of comments. The author will change over time and there may be multiple ones with different levels of contributions. The file name is often obvious.

/* 
 * 
 * This is the start of the next section.
 *  
 */
When you are dealing with big files, this sort of comment can be pretty helpful for the sake of readability.

/* WARNING - This part of the code may not work during day-light savings */
This warning type of comment is pretty useful. If you see a bug, it should help you figure out what part of the code needs changing. I also feel more comfortable changing code that I know is already buggy and hacky. It's already broken, so there's nothing to lose!

/* TODO: Update this code after database change is made. */
In the interest of always be shipping, I often add this type of comment. Similar to the warning type of comment, this one tells you what part of the code should probably be updated next.

git log
I've started using git more and more, and I think the comments that exist as commit messages are often the most useful. They often tell you why a change was made, which is nice. A more powerful feature is that commit messages are dated, and if you know when your bug first appeared this can help.

/* TODO: add more good and bad types of comments to this post. */

No comments:

Post a Comment