Categories
Game Development

Effective commenting

I’ve been dealing with a lot of code lately at work where I have to look again at stuff I last changed for some particular context 3-6 months ago. Either that change had a side effect or it broke some other edge condition. This is especially true with magic numbers, where I tweak the numbers […]

I’ve been dealing with a lot of code lately at work where I have to look again at stuff I last changed for some particular context 3-6 months ago. Either that change had a side effect or it broke some other edge condition. This is especially true with magic numbers, where I tweak the numbers until they work in one particular case in one particular level.

In general, for both myself and others, I see that the most effective comments are those that explain the why, rather than the how or what. Yet the most common type of comments explain the how or what, rather than the why.

For example
// Move foward on the balance beam
if (InDistance(10)) then PressStick(foward);

This is much better than nothing but I can usually figure it by in the context. Here’s another way to comment it

// This will ensure that we reach the threshhold range of grabbing the edge
if (InDistance(10)) then PressStick(foward);

With the first comment, I had no way to know if changing the 10 would have broke the code or if pressing forward had other effects. With the second comment, I could delete the code entirely and implement something else without breaking the dependency.

The golden rule of commenting IMO is to reveal intention. Code Complete says to comment variables over code but this is just an effect of commenting intention. Variables tend to reveal intention better than code does. I’m going to add this to my coding rules on the front page.

2 replies on “Effective commenting”

In terms of comments, Code Complete suggests the whole PDL (program design language) technique, where you literally don’t write code until your primary architecture is completely written in comment form.

You then go back through and add code corresponding to each comment. It’s awesome on paper, but difficult in practice. However, if you have an architecture in mind, you can literally “build” the entire system in PDL just to be sure you fully understand the planned solution. From that point, all you have to worry about are implementation details, and of course things you might’ve missed along the way.

Lately I’ve been commenting sections, rather than code or variables. This forces me to write comments before code, and thus document intention, rather than function.

Leave a Reply

Your email address will not be published. Required fields are marked *