5 Types of Comments to Avoid Making in Your Code

Have you ever been reviewing code and come across a comment that you deemed was unnecessary? Commenting your code is meant to improve the readability of your code and make it more understandable to someone other than the original developer.

I have identified 5 types of comments that really annoy me and the types of programmers who make them. I hope after reading this you won’t be one who falls into one of these categories. As a challenge, you can try to match up these comment programmers with the 5 types of programmers.

1. The Proud Programmer

public class Program
{
    static void Main(string[] args)
    {
        string message = "Hello World!";  // 07/24/2010 Bob
        Console.WriteLine(message); // 07/24/2010 Bob
        message = "I am so proud of this code!"; // 07/24/2010 Bob
        Console.WriteLine(message); // 07/24/2010 Bob
    }
}

This programmer is so proud of his code that he feels the need to tag every line of code with his initials. Implementing a version control system (VCS) allows for accountability in code changes, but at first glance it won’t be so obvious who is responsible.

2. The Obsolete Programmer

public class Program
{
    static void Main(string[] args)
    {
        /* This block of code is no longer needed
         * because we found out that Y2K was a hoax
         * and our systems did not roll over to 1/1/1900 */

        //DateTime today = DateTime.Today;
        //if (today == new DateTime(1900, 1, 1))
        //{
        //    today = today.AddYears(100);
        //    string message = "The date has been fixed for Y2K.";
        //    Console.WriteLine(message);
        //}
    }
}

If a piece of code is no longer used (i.e. Obsolete), delete it – don’t clutter your working code with several lines of unnecessary comments. Besides if you ever need to replicate this deleted code you have a version control system, so you can recover the code from an earlier revision.

3. The Obvious Programmer

public class Program
{
    static void Main(string[] args)
    {
        /* This is a for loop that prints the
         * words "I Rule!" to the console screen
         * 1 million times, each on its own line. It
         * accomplishes this by starting at 0 and
         * incrementing by 1. If the value of the
         * counter equals 1 million the for loop
         * stops executing.*/

        for (int i = 0; i < 1000000; i++)
        {
            Console.WriteLine("I Rule!");
        }
    }
}

We all know how basic programming logic works – this is not “Introduction to Programming.” You don’t need to waste time explaining how the obvious works, and we’re glad you can explain how your code functions – but it’s a waste of space.

4. The Life Story Programmer

public class Program
{
    static void Main(string[] args)
    {
       /* I discussed with Jim from Sales over coffee
        * at the Starbucks on main street one day and he
        * told me that Sales Reps receive commission
        * based upon the following structure.
        * Friday: 25%
        * Wednesday: 15%
        * All Other Days: 5%
        * Did I mention that I ordered the Caramel Latte with
        * a double shot of Espresso?
       */

        double price = 5.00;
        double commissionRate;
        double commission;
        if (DateTime.Today.DayOfWeek == DayOfWeek.Friday)
        {
            commissionRate = .25;
        }
        else if (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday)
        {
            commissionRate = .15;
        }
        else
        {
            commissionRate = .05;
        }
        commission = price * commissionRate;
    }
}

If you have to mention requirements in your comments, don’t mention people’s names. Jim from sales probably moved on from the company and most likely the programmers reading this won’t know who he is. Not to mention the fact that it everything else in the comment is irrelevant.

5. The Someday Programmer

public class Program
{
    static void Main(string[] args)
    {
       //TODO: I need to fix this someday – 07/24/1995 Bob
       /* I know this error message is hard coded and
        * I am relying on a Contains function, but
        * someday I will make this code print a
        * meaningful error message and exit gracefully.
        * I just don’t have the time right now.
       */

       string message = "An error has occurred";
       if(message.Contains("error"))
       {
           throw new Exception(message);
       }
    }
}

This type of comment is sort of a catch-all it combines all the other types. The TODO comment can be very useful when you are in the initial development stages of your project, but if this appears several years later in your production code – it can spell problems. If something needs to be fixed, fix it now and do not put it off until later.

If you are one who makes these types of comments or would like to learn best practices in comment usage, I recommend reading a book like Code Complete by Steve McConnell. This is one of the books that I recommend all programmers should own.

Or Perhaps you can learn how to stop commenting your code altogether.

Do you see any other unnecessary or annoying comments in your code? Please feel free to share.

Update (11/11/11): I found some additional funny code comments: 10 “Best” Code Comments

Related posts:

  1. My Experience at Orlando Code Camp 2011
  2. 10 Websites On How To Be A Better Programmer
  3. How To View Inception Through Code
  4. My Experience at Orlando Code Camp 2010
  5. Get Hired By Solving Programming Puzzles

Tags: , , , , , , , , , , , ,

54 Comments Leave yours

  1. seydar #

    I am a Life Story commenter. I complain about my girl problems through code.

  2. rms #

    public class Program
    {
    static void Main(final string[] args)
    {
    double price = 5.00;
    double commissionRate, commission;
    commission Rate = (DateTime.Today.DayOfWeek == DayOfWeek.Friday) ? .25 : (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday) ? .15 : .05;
    commission = price * commissionRate;
    }
    }

  3. You forgot about the non-nonsensical comment!

    /**
    This could work but it might not.
    TODO: Use the new API instead
    */
    if( !saveCache() )
    {
    throw new Exception(“Save failed”)
    }

  4. I love how anytime code is posted, someone will come along and offer a more efficient solution.

  5. Jeff #

    I’ve used the “Proud Programmer”, though less verbose, when performing an involved bug fix on a foreign codebase. I might tag comments with my initials and basic description of what change was made, or a bug number.

    This allows me to very rapidly find every change I’ve made. Of course, you might be able to handle this with source bookmarking, but only if your environment supports it well enough.

    After I complete my changes and verify functionality, I just search the codebase and remove all my comments, verifying that the surrounding comments are still correct.

  6. Bruce #

    How about this s**T makes no sense.

    //v1 — im going to have this run inside a new O.S. I’m designing next year ps it will be kernel-less

    >>>Starts VB

    lol maybe not that extreme but you get my point

  7. I dont see any problem with #5 – Someday Programmer. Its a perfectly alright comment saying why he had to do something yucky like that. And who knows he might revist it soon and fix it. Give the poor programmer a break.

  8. And the code commenter programmer:

    // string txt = “Hey world”;
    // string txt = “hi world”;
    string txt = “Hello, World.”;

    //for(i = 0; i < 10;i++)
    for(i=0; i<100; i++)
    {
    //MessageBox.Show("hey!");
    //MessageBox.Show("hi!");
    //MessageBox.Show("hello");
    MessageBox.Show("Hello World");
    }

    I was making some changes to an application for a client and that’s how the code looked like. :D

  9. I don’t want to condone poor programming practices – but typically more time is spent on trying to complete projects than trying to program more permanent but flexible code.

  10. Corey #

    The Someday Programmer should be commended for be able to write C# code several years before .NET was even released.

  11. This is no different than all the HR departments and Head Hunters that required 10 years .NET Experience back in 2002…

  12. Anonymous Coward #

    #1, 4, and 5 bespeak a certain ivory tower mentality on your part, I’m afraid to say.

    If you work in a perfect environment where you have all support tools you’d ever want, all your coworkers know them, and there is no management interference, then you’ll never need them. Back in reality, however, there are good reasons to use them.

    You may, for example, work with a veteran programmer who obtained his skillset before version control systems were commonly used and be asked to fix something in his code while he’s on vacation. A “proud programmer” comment then ensures that he knows who to talk to once he returns.

    Similarly, time pressure may make it necessary to put proper implementation of a feature off to the next version in favour of a quick and dirty hack, in which case it is very useful to document the shortcoming and the intention to fix it at a later date directly in the code as well as the bug-tracking system.

    Then there’s a whole ton of situations where a working environment develops in suboptimal ways. For example, two developers may work on the same working copy to avoid setting up a second test server for a small project, making version control annotations useless to find out who did what. This is not uncommon if you work with an aforementioned veteran coder or a career changer who does not drink and breathe version control. An intern may share a workstation with someone for a while. Hell, there may not even be a version control system.

    There are many situations where things are done quickly instead of properly, and it is irresponsible to rely on things that should be but aren’t. You write in comments what someone reading the code will need to know about it; that’s what they’re there for. Limiting your choices with generic rules is silly and dangerous.

  13. I love seeing comments like in production systems…

    string numDaysHistory = 5; //Change this before production
  14. drewp #

    “Chapters” instead of functions!

    function main() {
    // parse input
    rows = inputStream.splitlines();
    for (row in rows) {
    out.push(row.split());
    }

    // count distinct values
    some code that
    uses the same locals as
    the previous block

    // generate report
    if (0) {
    some big
    chunk commented out
    }
    // new report
    another
    big block
    that depends on some
    local set during the parse phase

    }

  15. Stephen Stillwater #

    I felt I had to post a link to this: http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html

  16. I appreciate your comment, but the point I am driving at is that programmers need the following: praise, criticism and feedback. Unfortunately within organizations, educating programmers on best practices is sometimes overlooked.

  17. I really like the life story programmer. Goos post.

  18. I am lucky enough not to work (currently) with anyone that codes like that. I haven’t always been that lucky though.:)

  19. This comment is totally superfluous but let’s keep it for compatibility reasons. One day I shall improve it. By the way, I don’t drink coffee. — Martin

  20. Adam #

    Don’t forget the passive agressive comment. Eg:

    // XXX: ouch. Bob in r20567 made me do this.

  21. Check out this comment:

    /**
    * Configuration options
    *
    * This file contains macros that pull various objects into the link
    * based on definitions in configuration header files. Ideally it
    * should be the only place in gPXE where one might need to use #ifdef
    * for compile-time options.
    *
    * In the fairly common case where an object should only be considered
    * for inclusion if the subsystem it depends on is present, its
    * configuration macros should be placed in a file named
    * config_subsystem.c, where @e subsystem is the
    * object basename of the main source file for that subsystem. The
    * build system will pull in that file if @c subsystem.c is included
    * in the final gPXE executable built.
    */

    I grabbed this from some Linux source code. What a waste, right? Boy, those newbies that work on Linux haven’t caught on to the latest fad of never commenting code! I have actually seen some files with more comments than code. Can you believe those morons?!

    To me, not commenting is a habit of developers who are either lazy, arrogant, inexperienced, not forward-thinking and/or just don’t work well on a team. In my 20 years of programming I’ve never run into any code over-commented the way you mention except #2. But, I’d hire any one of these guys over somebody who never comments.

  22. I pray that people do their best to use version control systems. They really are life-savers if you have to revert to old code.

  23. Greg #

    “The Proud Programmer”

    You assume that all developers check in their own code. This is often not the case, as junior (or even off shore resources) send their code to senior developers for code review as a patch. Its up to the senior developer to ensure that the code passes review and check it into the repository. Any shop that allows junior or off-shore resources total access to the code base is in for a few surprises :)

    Also, larger products usually have multiple code branches active at one point of time. The trunk will be receiving last minute bug fixes revealed in beta or even customer acceptance testing (they did what?) . At the same time another branch of the project may be getting major chucks of the first swipe of the next release. At sometime these need to be merged, and unless you want to spend major time hunting through blame and log files, the original developer is not easily identifiable as the vcs will identify the merger as the responsible party.

    Another downfall..what if you switch VCS systems? Working on a commercial product that can have a 10+ year life time, its a distinct possibility.

    “The Life Story Programmer”

    While your point is valid, it doesn’t reflect the reality of a business environment. Too many times, features/updates/bug fixes are decided upon in meetings, emails, hallway conversations and places like Salesforce cases. (Do not get me started on Product Management!!) . While its great to strive for excellent business and technical documentation, the reality is, no place is perfect. As a last resort if supporting documentation does not exist, let some future developer that has to maintain the code why it was decided to do something a particular way.

  24. I’m the someday programmer. It seems like everything I’ve ever made has a block of TODO comments at the top. For me personally it really does help keeping my project on track. But I’ve seen a few TODO comments stay in source for more than a year.

    For personal projects they get taken care of pretty quickly. I can just drop back in to the project 6 months later and there’s a nice list telling me what I need to do. At work they become a permanent part of the code as deadlines and other projects pull me away from “low priority” TODO items.

  25. commentfan #

    Granted there are useful and useless comments. All of the comment types above can be useful if trimmed a bit and focused a bit. Using meaningful names can cut down on the need. The most important to document is logic. The names can imply the purpose. Including the author name for the function is important in a multiple coder project.

    The real test is having someone else make necessary changes to your code. Try making changes to your own more intricate code, efficiently after three months.

    I equate lack of comments with hubris, or laziness. I equate commenting with class and professionalism.

  26. lalbatros #

    … books that I recommend all programmers should own …

    I liked to have a look at some of these books, specially the table of content.
    However, should programmers really own any book at all?
    I have bought so many books that I throwed away without reading more than 10 pages!
    Quite often, the 4 days express delivery by Amazon was too long and when I received the book I did not “need it” anymore.

    It is by far more important to master the domain of application.

  27. What about the mysterious comment:

    // Sleep for 2 seconds
    Sleep(2000);

    with no indication of why!

  28. I’m with the Jason Above me…

    // TODO: Must get back here and add trim this code up
    To me, comments like this are a diary of what is/was and maybe should be going on with the code in question. code to me isn’t a one time – fire and forget;never see it again.. in my 20+ years its like molding clay… sure sometimes you write stuff and never see it again..

    I’d do not get annoyed with comment dissertations; I mean it takes a couple minutes to place that good stuff into documentation (A chore for Juniors perhaps) … I have found my own little paragraphs to myself have been very handy in helping me pick up a chunk of code I haven’t stared at in months; get up to speed; and continuing like I never missed a beat.

    Now comments I consider silly are the coffee examples etc. Or ones that explain things that are explained just by being able to understand code a bit (For loop example – is silly… but something like:

    // NOTE: The below construct is ugly but it’s used because it actually saves clock cycles considerably… it really equates to iVal(SomeText) but the some text is buried in a thick nest of classes and pointers etc. We’re avoiding a bunch of methods and property code by just letting the compiler work out the pointer math for us in one fell swoop.

    ….Once in awhile like to pop in a little humor into my comments – it often gets me a laugh at a later date and is sometimes rewarded with another developer calling me and telling me how I caused a chuckle…

    Again I agree with the Jason above me… I prefer comments over not having them… you can delete them if you don’t like them.. but you can’t make them up when you wish they were there! B^)

  29. Ryan #

    #3 is actually pretty useful if you often switch languages / frameworks. For example with loop indexers, in some languages they’re 0-indexed and some 1-indexed.

    When you have to support projects built in a mix of C#, Java, JS, VB6, VBA, VB.net, PHP, pascal, TSQL, PSQL, python, actionscript not to mention several DSLs then it really is handy to document the basics. Sure, you shouldn’t do it all through your code (I try and keep it in a single function, or specifically add a readme.txt to the source) but it isn’t worthless.

    #3 is also handy if you’re working with a new technology, language or framework. I find building a demo project complete with ample comments helps me learn the language, and it’s also great for future reference. For example we’ve recently started using Fluent nHibernate for nHibernate mappings; I’ve documented the first use of all of the methods, along with the reasons for using them and where applicable the alternatives. Those comments exist in but one place, but are really handy when my colleagues need to add stuff. They’ve gotten up to speed really fast because I’ve prepared everything for them :)

    I’m also a bit user of TODOs. You just have to manage them well. Use them only when the work your delaying is either big, or hard to estimate at the current time. Then regularly go back and remove them – either by finishing the work, or if you don’t need to by deleting.

  30. Adrian Tawse #

    I heartily agree with your article. I recount one depressing incident where I had written what I considered perfectly clear readable code requiring no comments whatsoever. On code review I was INSTRUCTED to comment every line. I enjoyed myself inserting the most assenine comment I could thing of on every single line. It passed review. Don’t always blame the programmer, sometimes we are obliged to be stupid.

  31. // TODO: Insert comment here!

    ^ I have actually seen this in an internal-use application before!

  32. I agree with 1 – 4, but 5 cannot be avoided in some cases as the information available to resolve a problem is not available. It is always best to make this comment for a TODO than miss it out

  33. Martin #

    #2 is very useful when you’re working in a team environment, as it communicates to others who might look at the code why it was neccessary to remove it, this then stops them adding it back in/rolling the code back unneccessarily.

    The alternative is for them to realise a bit of code has gone missing, try and track down the commit that removed it, find out who was responsible and ask them why it has gone. That’s what perfect colleagues might do, but how many of us have those?

  34. Patrick #

    #2 – I never remove unnecessary/obsolete code. I usually create a “Deprecated Code” #region/#endregion at the bottom of the class and put the old code there, along with my initials, date/time and a comment stating why it’s no longer needed. But that’s just me :)

  35. Every once and a while I see a comment which is totally illogical and makes perfect sense at the same time. This came from a contractor:

    typedef uint16_t millisecond_t; // Note that there are 1024 milliseconds in one second

  36. “Commenting your code is meant to improve the readability of your code and make it more understandable to someone other than the original developer. ”

    I totally disagree with this statement, and with some of the other 5 descriptions.

    My code is “My code” and I can comment it however I want. If you specify that this is intended to pertain only to corporate code, then maybe the statement above may be partially valid.

    I routinely pull up code I wrote on the 80′s to modify it, and the massive commentary I originally added to the code helps me understand what I was thinking at the time.

    For some corporate environments, by edict, deleted code must be preserved in-place, but conditionally not assembled/compiled.

  37. Jim #

    I gotta say I disagree with some of the comments made. For instance – in the life story programmer – you said the rest was irrelevent. I think you missed a very important point. What isn’t important (unless it’s really tricky – and then you might want to rethink anyway) is *how* you did something – that’s right there in the code. What is important is *why* you did something. It might prove you weren’t just a misguided idiot after all. So – in the example – sure leave out the details – but leave in the requirement. Because 5 years down the road (if you write anything worth running 5 years later) – noone’s going to be able to find the separate requirements document – let alone be able to figure out what lines of code did that.
    And the comment about “fix it now” – obviously you’ve never developed code for a living – meaning you’ve never been on a schedule that doesn’t allow for perfecting everything right now.
    //TODO Stop reading any articles that are entitled “X things about X”. They are invariablty just some author throwing down opinions when they can’t think of anything relevant to write. IMHO. :)

  38. triptyx #

    My favorite comment of all time (and by favorite I mean I had to spend 30 minutes composing myself so I wouldn’t go kick the crap out of the guy) was a programmer that was new to our shop and did a 30-line ASCII art comment of his name in the middle of the code.

    Urge to kill rising…..

  39. That’s awesome… a fascinating display of programmer boredom!

  40. Danny #

    a comment from our production code:

    // Anatoly is GAY

  41. Hartvieg #

    Since the target audience for comments is typically other programmers if the code can be read and understood I don’t think comments are necessary. Rehashing the obvious just creates a maintenance issue.
    I would much rather see a comment that explains “why” rather then “what”. If the “what” is complicated a higher level explanation could be added provided there isn’t a design document that already handles this. I know many times there is either no design documentation or “that old thing was only used for initial development.” Unfortunately comments need to be maintained just like the rest of the code or they become worthless.

    This only holds if the target audience is another programmer. I can see by some of the other posts the target could simply be for the sake of amusement. In my distant past I remember stepping through some code and getting to a comment that said:
    “If we get here, we are bumming”
    That created a nested bummer as it took quite some time to figure out why we were “bumming” at that point in the code.

  42. TS #

    Actually, “The Someday Programmer” type of comment isn´t that bad at all and I´m using it rather regularly in situations where the general direction is clear, but current demands aren´t completely settled:

    Customer A needs solution X1 right now, customer B has shown interest in a similar solution X2 but it is pretty unsure whether he will actually need/use/pay someday. Thus, there is neither time nor the need to implement the additional features for X2 now, thus inserting “the someday programmer” at the right place comment helps me to find it again in the future. And in fact, “someday” has turned into “today” pretty often after a couple of months, maybe then needed for a different customer C or another similar solution.

    I agree with the fact that a “someday” comment isn´t a good solution for a potential bug, especially if there isn´t any way of handling the potential error case or checking whether the problematic case actually occurs during development-level testing (log message, debug assert,…).

  43. cm #

    I’ve seen commented out code in production.

    One case was a one liner to put in a timeout. It was “removed” because invoked code in a dll needed to do the timeout instead. It was difficult to debug to find why the app was ending.

    So two problems – the line was just commented out, and no reason for that was given. Inviting anyone in the future to re-enable the code and create the problem all over again…

  44. Vince #

    My top comment that I have found after getting a report from our Customer Support people that something wasnt working is this:

    // Code goes here..

    This has now become a kind of in-joke when someone raises a problem in an area that we suspect the same ex-programmer worked on :)

  45. I wrote about commenting a while ago based on advice from the Elements of Programming Style:
    http://tech.bluesmoon.info/2008/05/commenting.html

  46. Thanks for sharing. I’m about 10% some day programmer!

  47. Nice :-) I haven’t read Code Complete but Clean Code by Uncle Bob has a good chapter about using comments.

  48. 6. The Deadline Programmer
    I’m doing this because I’ve got a deadline to make. It works. If you don’t like it today or in the future, I don’t give a fuck, unless I’m still on this project.

  49. Eric #

    The best comments I’ve seen in a source file from the codebase of a (well known) company I worked in were about some Tex-Mex restaurant that a team of developers especially liked. There were comments on the special hot sauce “maison” as well as the address and directions to the restaurant.

    Stumbling upon some humor was very pleasant :-)

    I like to detect some traces of humor in existing code. I think it makes it more readable ;-)
    (I’m almost serious: I think it establishes a closer and more human relation with previous developer. You then see his code differently…)

    Eric

  50. Patrice Stoessel #

    about TODO : it shows important things, i don’t think it sould be a comment …
    in my code (C/C++), i defined TODO as a macro (taking a message as parameter)

    TODO is like a failed assertion meaning “code is not complete”
    the actual behavior depends on what we’re doing :

    during developpement and test mode, when executed, the behavior of the macro is to throw an exception meaning :
    we’re going through some unfinished code, you developper should correct it right now

    in production mode (run by customer), the behavior can be customized with a configuration file :
    - throw an exception
    - pass silently
    - any other possibility, depending on the needs of the customer

5 Trackbacks

Leave a Reply