Coding Style – Recommendations for Commenting Code Effectively

coding-stylecomments

I want to hear from you any advice and experience of writing comments in your code. How do you write them in the most easy and informative way? What habits do you have when commenting parts of code? Maybe some exotic recommendations?

I hope this question will collect the most interesting advices and recommendations forcommenting, something useful that everyone can learn from.

OK, I will start.

  1. Usually, I don't use /* */ comments even when I need to comment many lines.

    Advantages: code visually looks better than when you mix such syntax
    with one-line comments. Most of IDEs
    have an ability to comment selected
    text and they usually do it with
    one-line syntax.

    Disadvantages: Hard to edit such code without IDE.

  2. Place "dot" in the end of any finished comment.

    For example:

    //Recognize wallpaper style. Here I wanted to add additional details
    int style = int.Parse(styleValue);
    //Apply style to image.
    Apply(style);
    

    Advantages: Place "dot" only in comments that you finished. Sometimes you can write temporal information, so lack of "dot" will tell you that you wanted to return and add some additional text to this comment.

  3. Align text in the enumerations, commenting parameters etc.

    For example:

    public enum WallpaperStyle
    {
        Fill = 100,     //WallpaperStyle = "10"; TileWallpaper = "0".
        SizeToFit = 60, //WallpaperStyle = "6";  TileWallpaper = "0".
        Stretch = 20,   //WallpaperStyle = "2";  TileWallpaper = "0".
        Tile = 1,       //WallpaperStyle = "0";  TileWallpaper = "1".
        Center = 0      //WallpaperStyle = "0";  TileWallpaper = "0".
    };
    

    Advantages: Just looks better and visually more easy to find what you need.

    Disadvantages: Spending time to align and harder to edit.

  4. Write text in comment that you can't obtain by analyzing code.

    For example, stupid comment:

    //Apply style.
    Apply(style);
    

    Advantages: You will have clear and small code with only useful information in comments.

Best Answer

Some of the statements below are quite personal, though with some justification, and are meant to be this way.

Comment Types

For the brief version... I use comments for:

  • trailing comments explaining fields in data structures (apart from those, I don't really use single line comments)
  • exceptional or purpose-oriented multi-line comments above blocks
  • public user and/or developer documentation generated from source

Read below for the details and (possibly obscure) reasons.

Trailing Comments

Depending on the language, either using single-line comments or multi-line comments. Why does it depend? It's just a standardization issue. When I write C code, I favor old-fashioned ANSI C89 code by default, so I prefer to always have /* comments */.

Therefore I would have this in C most of the time, and sometimes (depends on the style of the codebase) for languages with a C-like syntax:

typedef struct STRUCT_NAME {
    int fieldA;                /* aligned trailing comment */
    int fieldBWithLongerName;  /* aligned trailing comment */
} TYPE_NAME;

Emacs is nice and does that for me with M-;.

If the language supports single-line comments and is not C-based, I will be more enclined to use the single-line comments. Otherwise, I'm afraid I've now taken the habit. Which isn't necessarily bad, as it forces me to be concise.

Multi-Line Comments

I disagree with your precept using single-line comments for this is more visually appealing. I use this:

/*
 * this is a multi-line comment, which needs to be used
 * for explanations, and preferably be OUTSIDE the a
 * function's or class' and provide information to developers
 * that would not belong to a generated API documentation.
 */

Or this (but I don't that often any more, except on a personal codebase or mostly for copyright notices - this is historical for me and comes from my educational background. Unfortunately, most IDEs screw it up when using auto-format):

/*
** this is another multi-line comment, which needs to be used
** for explanations, and preferably be OUTSIDE the a
** function's or class' and provide information to developers
** that would not belong to a generated API documentation.
*/

If need really be, then I would comment inline using what I mentioned earlier for trailing comments, if it makes sense to use it in a trailing position. On a very special return case, for instance, or to document a switch's case statements (rare, I don't use switch often), or when I document branches in an if ... else control flow. If that's not one of these, usually a comment block outside of the scope outlining the steps of the function/method/block makes more sense to me.

I use these very exceptionally, except if coding in a language without support for documentation comments (see below); in which case they become more prevalent. But in the general case, it really is just for documenting things that are meant for other developers and are internal comments that really need to really stand out. For instance, to document a mandatory empty block like a "forced" catch block:

try {
    /* you'd have real code here, not this comment */
} catch (AwaitedException e) {
    /*
     * Nothing to do here. We default to a previously set value.
     */
}

Which is already ugly for me but I would tolerate in some circumstances.

Documentation Comments

Javadoc & al.

I'd usually use them on methods and classes to document versions introducing a feature (or changing it) especially if that's for a public API, and to provide some examples (with clear input and output cases, and special cases). Though in some cases a unit case might be better to document these, unit tests are not necessarily human readable (no matter what DSL-thingy you use).

They bug me a bit to document fields/properties, as I prefer trailing comments for this and not all documentation generation framework support trailing documentation comments. Doxygen does, for instance, but JavaDoc doesn't, which means you need a top comment for all your fields. I can survive that though, as Java lines are relatively long anyways most of the time, so a trailing comment would creep me out equally by extending the line beyond my tolerance threshold. If Javadoc would ever consider improving that, I'd be a lot happier though.

Commented-Out Code

I use single-line for one reason only, in C-like languages (except if compiling for strict C, where I really don't use them): to comment-out stuff while coding. Most IDEs will have toggle for single-line comments (aligned on indent, or on column 0), and that fits that use case for me. Using the toggle for multi-line comments (or selecting in middle of lines, for some IDEs) will make it harder to switch between comment/uncomment easily.

But as I'm against commented-out code in the SCM, that's usually very short lived because I'll delete commented-out chunks before committing. (Read my answer to this question on "edited-by in line comments and SCMs")

Comment Styles

I usually tend to write:

  • complete sentences with correct grammar (including punctuation) for documentation comments, as they are supposed to be read later on in an API doc or even as part of a generated manual.
  • well-formatted but more lax on punctuation/caps for multi-lines comment blocks
  • trailing blocks without punctuation (because of space and usually because the comment is a brief one, that reads more like a parenthesised statement)

A note on Literate Programming

You might want to get interested in Literate Programming, as introduced in this paper by Donald Knuth.

The literate programming paradigm, [...] represents a move away from writing programs in the manner and order imposed by the computer, and instead enables programmers to develop programs in the order demanded by the logic and flow of their thoughts.2 Literate programs are written as an uninterrupted exposition of logic in an ordinary human language, much like the text of an essay[...].

Literate programming tools are used to obtain two representations from a literate source file: one suitable for further compilation or execution by a computer, the "tangled" code, and another for viewing as formatted documentation, which is said to be "woven" from the literate source.

As a side note and example: The underscore.js JavaScript framework, notwithstanding non-compliance with my commenting style, is a pretty good example of a well-document codebase and a well-formed annotated source - though maybe not the best to use as an API reference).


These are personal conventions. Yes, I might be weird (and you might be too). It's OK, as long as you follow and comply to your team's code conventions when working with peers, or do not radically attack their preferences and cohabitate nicely. It's part of your style, and you should find the fine line between developing a coding style that defines you as a coder (or as a follower of a school of thought or organization with which you have a connection) and respecting a group's convention for consistency.

Related Topic