Monday, July 2, 2007

Code Comments

When I first started writing software the common mantra was to put in lots of comments. At times I did this and other times I didn't. During most of my career I have worked on code bases that someone else started. In that time I have rarely seen code comments that really helped. Often I see comments that basically restate in English what the code is already saying. Even worse the comments tell me that the code does something different than what it actually does.

In more recent years I have found myself reading comments as a last resort. Usually this is after I have determined that the code isn't working the way it seems like it should. At this point I'm looking for a clue as to what the original author, sometimes myself, was thinking when they wrote the code.

So, long story short, if you feel like you need to write a comment to clarify some code, you probably need to rewrite the code so that it is more readable. Every once in awhile I get someone who is asking me to put in comments to clarify what is going on. As it turns out, usually the problem is that what I thought was obvious when I wrote it wasn't. This makes it very difficult to comment code effectively.

Which gets to the point of my post. Learn to read code. No matter what language you are using, you need to be fluent in both writing and reading the language. To be really fluent you need to read code written by a large number of writers. What you will find is that there are certain dialects that creep into language. The more code you read the better you will be at figuring out what is wrong with a program.

Ultimately, the speed at which you can correct problems in your and others code will translate into how valuable you are as an engineer.

The other side of this is to write self documenting code. This usually involves reasonably descriptive variable names. Beware of too long names as this can also detract from readability.

Package up logical things into functions or methods that do only one thing. That way it is really clear what is happening.

Mostly just use common sense and keep things simple.

No comments: