Thursday, February 2, 2012

Commenting For the Future

What, me comment?


You are in the middle of a large coding project.  You've got the entire design in your head, and you are banging out lines and lines of code.  You've done your best to name your functions and your variables clearly.  It all seems so obvious, why would you need to add comments too?

The simple answer is: "What you know now is not what you'll know later.".  Another simple answer is: "You aren't the only one maintaining the code.".  No matter how obvious something seems to you now, it isn't going to be obvious to the next person who comes along, even if that person is you!

Comments have a definite purpose.  They are a road map for future usage.  If done properly, comments can help you restructure the code, and keep your functionality tidy.

What To Comment
Modules: Every source code module needs a paragraph describing the content of the module.  This allows people to find the proper module to look for a function, and directs them to the proper place to put a new function.

The comment should describe the general usage of the module, and what types of functionality should be found in this module.  If applicable, it can give a general idea of where in an architecture the module belongs.

Functions: Every function in a source module needs a paragraph describing when to call the function, what the operands are, what input and output are expected.  This is also a good place to describe interactions with other parts of the code.  If this function can't be called until some part of the architecture is initialized, then put that in the paragraph.  If this function relies on code sequences elsewhere in the product, add that too.  No one should have to read the code for an entire product to figure out what is happening.

Code: Code should have comments when there is a reason to have comments.  If the code is tricky to understand, or it has some non-obvious code interactions, write that down—don't make other people figure it out the hard way.

If you've had to break up logic, then comment it so the flow is obvious.  You can also use code comments to describe what conditions would lead to the code, and remind you of issues that exist in the code.

You should definitely leave comments behind about suspicious code sequences, code that you recognize is error-prone or overly delicate.  Remind yourself of code that needs rewritting or moved.  You can't always take care of all problems immediately when you are looking at code, but if you leave a note you can always get back to it.

Avoid stupidly obvious comments like:

rc = 0;    /* no error yet */
myVar = value;   /* copy because we need this later for <some reason> */

That's just clutter.  You want your comments to be meaningful and worthwhile to read.

Comments are necessary.  There isn't a programming language in existence that makes the "why and how" of code obvious enough to avoid comments.

No comments:

Post a Comment