.NET Coding Guidelines – Commenting

Let’s be honest, there’s only one main purpose to blogging. To translate concentrated rage into HTML. To that end, I humbly offer a series of guidelines to you shoddy developers who regularly infect my source tree with your twisted code-wrongs.

Part 1 — Comment your .NET code

You might very well think that. I couldn’t possibly comment.
Francis Urquhart

By glancing at your uncommented code I can tell instantly that you’re either an amateur or, more likely, a lazy and selfish sociopath. It’s not like I’m asking you to write a novel. Would it really impede your productivity so much that you can’t find time to furnish your garbled, obfuscated nonsense with some sort of mitigating explanation? Oh, and when I tell you to start adding comments, I don’t expect you to start littering code with superfluous crap like:

populateControls();       // populate the controls
string name = getName();  // set the name

Comment as you go along, or you’ll forget. If you’re so inclined, use comments to structure your functional design before you write code, this is the Pseudocode Programming Process. As a general rule, comment what your code is doing, and why it’s doing it. I should already be able to see how your code works, because you’ve used meaningful and precise names for your classes, functions and variables.

// create a SqlConnection object using connectionString
SqlConnection cnn = new SqlConnection(connectionString);

I can see you’re using a SqlConnection because the programming syntax conveniently forces you to include the class type in its variable declaration. It is also very clear from the code that you’re passing connectionString as a parameter. The bigger picture is a mystery. What is your intent? Why are you connecting to the database? What data are you expecting back? If these things aren’t clear then explain.

Don’t comment every single line, instead give a brief summary for each block of related code. If you’re working on an API then use a documentation generator like Javadoc or SandCastle and format comments accordingly.

Other people will probably have to extend or maintain or your unintelligible mess. You might think it’s good for job security if you’re the only one who can understand your code. It really isn’t.

Read more about commenting code:

Follow up post:

22 Responses to “.NET Coding Guidelines – Commenting”

  1. CMU Says:

    Well said that man. So many coders. So few commenters.

    I have an aditional rule of thumb: The verboseness of your comment should be roughly proportional to how unusual the piece of code is or how unexpected its behavior is. For example:

    // Draw red thumbnail border
    this.lineStyle(1, 0xFF0000, 100);
    this.moveTo(100, 100);
    this.lineTo(200, 100);
    this.lineTo(200, 200);
    this.lineTo(100, 200);
    this.lineTo(100, 100);

    // Check for day and week changeover
    // Note that this approach only works for files that have at
    // least 1 hit per day. This isn’t a problem for the majority
    // of our content, but dead projects may roll low
    // hits per days or week into one.
    if (curDate != date) { …

    Note the first comment is short, and the code is a few lines long. Drawing boxes is simle enough though and doesn’t do anything unexpected. The second comment is only talking about a single simple-looking ‘if’ statement, but it has implications to how the system operates and potential bugs. Hence the long verbose statement.

    If you get into the habit of doing this, you can tell if you’re having a lack-of-thought day by the number of multiple-line comments you end up writing. If its lots, you’re probably overcomplicating things.

  2. Ciz Says:

    Great rule of thumb. If you need to explain everything then your original design might need revising. Intelligible code isn’t just well commented, it’s well designed.

  3. Unhygienic .NET code « Charismatic Megafauna Says:

    [...] Comment your code, even if you just add markers to roughly indicate what each group of statements is doing.  It’s painstaking to trawl though thousands of lines of uncommented code trying to work out what each bit does. [...]

  4. Mads Kristensen Says:

    If you look at code written by someone else, you can easily see if the code is good just by looking at the commnents. If they are good, then the code is also good. You might want to check out http://blog.madskristensen.dk/post.aspx?id=2887fd12-bb4e-4ab8-b55c-908ab8e29bee which touches many of the same points as your article.

  5. foobar Says:

    “If the comments are good, the code is good”?!?

    Sorry, but this is utterly untrue. Obviously you have never maintained any sort of non-trivial system in your lifetime. Try debugging some of the drivel coming out of SAP sometime and tell me that statement again.

  6. Mads Kristensen Says:

    As a rule of thumb, it usually holds water that quality comments are written for quality code. That’s my experience.

  7. Jim Bolla Says:

    From my experience, most of the time a block of code needs comments is because it’s not properly refactored and is violating the Single Responsibility Principal. Since the blog post doesn’t provide any good code examples of where a code comment is warranted, I will use the first post comment’s example…

    // Draw red thumbnail border

    should be
    private void DrawRedThumbnailBorder()
    {

    }

    Now the code is more self documenting and the action of drawing a red thumbnail border has been isolated from surrounding code.

  8. Ciz Says:

    I tend to agree with Mads, In my experience, good comments are usually correlated with good code, but there’ll always be painful exceptions.

    Jim Bolla – I agree with your example in principle, but don’t think it’s necessarily as simple as that. You wouldn’t want DrawRedThumbnailBorder, DrawYellowThumbnailBorder() etc. so you might write something more general like DrawThumbnailBorder, DrawRectangle, DrawPolygon, or something else depending on how the code is to be used, and that decision is key to good design.

    Even assuming DrawRedThumbnailBorder is suitable, you might sometimes want to add a note explaining why you’re drawing the border, e.g.

    // Draw a border around this thumbnail because it’s currently selected.
    // Red makes it stand out against the black background, and also matches the client’s color scheme.

  9. B3ardman Says:

    “Even assuming DrawRedThumbnailBorder is suitable, you might sometimes want to add a note explaining why you’re drawing the border, e.g.
    // Draw a border around this thumbnail because it’s currently selected.
    // Red makes it stand out against the black background, and also matches the client’s color scheme.”

    Not entirely convinced by that.

    You might like:

    private void HighlightCell ()
    {
    DrawThumbnailBorder ( selectedCellColor );
    }

  10. Ciz Says:

    Re: HighlightCell() – maybe, again it depends on how you your program will reuse different parts of code, and that’s more to do with good design. Instead, you might have a generic HighlightElement, or a more abstract HighlightTumbnail. However, none give any indication why a particular cell is being highlighted, which is where comments are useful.

  11. Donn FElker Says:

    Comment as you go, otherwise it will never get commented.
    How many times have you ever seen someone go back and comment code they wrote 2 months ago? Yeah. Right.

  12. Will Asrari Says:

    I don’t know about all of this code commenting. Code should be written in a way that doesn’t require commenting. If you have relevant class, method, parameter, member variables, etc… you shouldn’t really HAVE to include comments. A summary for each method / class should be sufficient enough.

    Maybe I just work with developers who don’t need their hands held. I don’t know…

  13. Ciz Says:

    Will – I almost agree. Perfectly designed and refactored code shouldn’t need much further explanation to describe *what* it’s doing, because you can infer that from accurate and carefully chosen names. However, none of this helps you understand *why* the original programmer made certain design choices or assumptions.

  14. Geoff Says:

    No matter how you look at it, code is still a “code”… and is no replacement for natural language. Even when I come back to do some maintenance on my code months after the fact, I don’t want to have to sit there and translate a bunch of C# to my original intent. I want to be able to scan the comments to understand the logic. It’s MUCH quicker that way.

    I agree with the basic approach that you should always succinctly comment your intent. In my experience, I find that if a developer can’t “touch-type” they’re less likely to comment their work.

    Also, on one project I did I received very positive feedback from a happy client that was something to the effect of “I don’t know C#, but I could understand what was going on.”

    Commenting now is all about future productivity.

  15. Eric Says:

    “Code should be written in a way that doesn’t require commenting.”

    Will, you hit the nail on the head. Comments are never an acceptable substitute for well-written readable code. I would even go the extra mile to write less efficient / easily comprehensible / easily maintainable code than to have an extremely code-efficient piece of code that nobody can understand.

    The most useful commenting that anyone can do is to choose your method names and member names descriptively and carefully.

    Comments are useful to explain non-obvious techniques, and to give a short, general purpose statement for a piece of code — the fewer the comments required the better.

    The inherent problem with comments is that they can never be tested. Code can be tested, but comments cannot. Once comments are created, they must be maintained along with the code (adding to the burden of software maintenance), or else they will become a liability to the code. I have inherited code from other developers that did not match the code! I don’t know if it was just commented incorrectly to begin with, or if the “comment rot” was contributed by people not maintaining the comments after software changes were made.

  16. If the code and the comments disagree, then both are probably wrong « Charismatic Megafauna Says:

    [...] recently wrote some code commenting guidelines to explain why comments are usually a Good Thing. Some intelligent and good looking people agreed [...]

  17. Dustin Says:

    “// Draw a border around this thumbnail because it’s currently selected.
    // Red makes it stand out against the black background, and also matches the client’s color scheme.”

    And what happens to your comment when someone changes the color scheme?

    “No matter how you look at it, code is still a “code”… and is no replacement for natural language.”

    I look at it the exact opposite way. I can actually read code and understand what it’s doing. People have a very difficult time understand things. I’d rather see this:

    if(element.isSelected()) {
    highlight(element);
    }

    Than:

    // Draw a red box around the selected element.
    [imaginary code to find the selected element and position the drawing cursor near it]
    this.lineStyle(1, 0xFF0000, 100);
    this.moveTo(100, 100);
    this.lineTo(200, 100);
    this.lineTo(200, 200);
    this.lineTo(100, 200);
    this.lineTo(100, 100);

    I generally read comments as an excuse for not being able to do something correctly. I certainly *write* them that way. Browsing through my code you’ll find a lot of what appears to me to be obvious (with documentation comments on public interfaces). The non-documentation comments describe why I couldn’t make something obvious for whatever reason (broken APIs, performance problems, etc…)

    I’ve read many misleading comments in my time, and I’d really just rather not have some English lying to me about code I can already see.

  18. Will Asrari Says:

    “I generally read comments as an excuse for not being able to do something correctly.”

    lol. Where I’m from we refer to that as a “stove-pipe” system. That or a “duct-taped piece-of-sh*t”.

    Eric: If a client REQUIRES comments (some do) then I tell them that I won’t add them until AFTER they agree on the software and check off that it is exactly what they want per the scope of the project. That way I don’t have to maintain / update comments. In that respect Eric, YOU hit the nail right on the head!

    Personally I think the following method is commented enough just by naming conventions and constraints alone.

    public static T CalculateMax(T first, T second) where T : IComparable
    {
    return second.CompareTo(first) < 0 ? first : second;
    }

  19. grethen Says:

    well done and useful content :)

  20. legend of mir Says:

    Let’s be honest, there’s only one main purpose to blogging. To translate concentrated rage into HTML.

    PMSL!!!!

  21. iisrael13 Says:

    Hello
    Can you giv me Post a comment cods?

    My email is: iisrael13@yahoo.com

    Thank you!

  22. sandrar Says:

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.


Leave a Reply