Archive for April, 2010

Code commenting style

Sunday, April 4th, 2010

After programming for more than ten years I gradually refined my commenting style to a level that I am satisfied with, at least for now. Long story short, this is an example for C++:

// This is a comment.

Simple and precise. Let me explain why. The general format follows this pattern:

1. Comment character(s), such as /*, //, #, %.
2. Space.
3. Comment string, that starts with a capital letter (with rare exceptions).
4. Period.
5. Comment closing character, such as */, –>

1, 3, and possibly 5 must be present in any comment. Let’s focus on the parts that can be present or omitted. I include Space before the comment string to differentiate between a comment line and a commented out code:

// Use it as follows:
// exec(true);
//exec(yFlag);

In the example above, the first two lines are comments, because there is a single space before the comment string. The last line is a commented out line of code.

I use capital letter to start a comment and a period after a comment sentence for multiple reasons. First, it forces to make comments from well formed sentences, which can be easier to understand as compared to incomplete sentences. Second, it tells me where a comment sentence starts and ends. For example, if I see a comment line that does not end with a period, then I can assume the next comment line must continue the same sentence. For example:

// This is one
// comment sentence.

To recap. A space before helps separate at a glance comments from commented out code. Following a formal sentence structure (start with a capital letter and finish with a dot) helps to understand the comments better and provides information about where the comments start and end.