Comments

Commenting your code is of great value if you (or anyone else) ever intends to look at your code in the future. Hopefully this is the case. But what do you write? What is important to include and what do you exclude? Lucky for you, I know the answer.

What to include

Put into your comments anything that will help you figure out why your wrote this code. Let me repeat myself. Tell the reader WHY this code exists.

Why is why so important? Most coders can read the code and determine what the code does at a basic level. I once worked on a piece of code that was very well written. Meaningful variable names, lot's of comments, nicely indented: generally well written. One problem: It was all in German, which unfortunately, I can't read. I was forced to read the code and understand its function, which I did. I successfully fixed the problem without the comments. Didn't I just prove comments aren't necessary? No, I proved they aren't required to understand function.

Why is useful at a much bigger level than the what of a piece of code. The why tells you how this fits into the bigger picture. It tells you its purpose.

You can put in a quick summary of what a method does and even explain the parameters to the method. I'm not opposed to any of that. If the code is particularly complex or confusing (perhaps a rewrite is in order) then the what can have some value. The purpose of a thing is far greater, since it explains the reason for its very existence. This does not change as the code is maintained. Code that is no longer necessary gets removed along with the comments.

What to exclude

Don't explain the obvious. Such comments are of zero value and tend to get out of sync as the code evolves.

Don't say in great detail what code is doing. When you do that you increase the maintenance load since not only the code needs to be updated, but so do the comments.

Examples of Bad Comments

$a = $b; // set the variable 'a' to the value of variable 'b'. Variable 'b' remains unchanged.

The comment states the obvious and as such has no value. if the name of $a or $b ever changes, then the comment becomes junk.

sort($names); // reallocate the array

The comment here is vague and as such reveals nothing.

Examples of Good Comments

$first = substr($name, 0, 1); // we need the first letter of the name as a key

The comment explains why we are taking the first letter from the name.

$img = SITE::file($file, 'images'); // find the site specific image

The comment here explains the purpose of this call.

How Many Comments?

Add only the number of comments necessary to explain the code. A good test is trying to read only the comments and see if you can determine the nature of the code. If you can't, perhaps you need more. If there are more comments than lines of code, perhaps you need less. I know, that isn't very scientific, but it is fairly practical.