Is commenting your code useless?

October 15, 2009 – 6:19 pm Tags:

James Carr has written a well argumented post about comments. To sum it up shortly, he says comments are the lowest form of communication, and that commenting freshly written code is not a good idea.

I tend to disagree, and here’s why.

Arguments against commenting

James puts it quite well: When you write comments, it would be much better idea to just talk with your coworkers about it. He uses “excuses” as an example – code which does something that you need to explain, or says something like “Here we do X but we should really do Y”

While I partially agree – if you’re not sure which approach you should use, or whether your approach is correct, talking with your coworkers is definitely a good idea.

While James doesn’t directly say that you should not write comments, it does sound a little like it. He does point out that instead of having comments, code should be self-explanatory and self-documenting. While having code like that is definitely a good thing, sometimes you just need comments.

When comments go bad

Before we look at reasons to write comments and good commenting style, let’s take some examples of bad and useless comments.

//Set user's name
$user->name = 'Spike Spiegel';

Is this a good comment? If you said no, you’re right.

The reason this is a bad comment is that it does not add anything useful. The comment is merely repeating what the code says. It’s quite obvious to anyone who has written code that in the above case we are indeed setting the user’s name – even if the comment was not there.

$value = 'bad'; //FIX THIS

How about this one? Nope.

This one is bad because nobody will ever fix it. That’s right, even though it says fix me, and it’s written in all caps, nobody will still fix it. Why? Because it’s not very likely they know what’s wrong with it, and because it’s not very likely to get noticed. Things that need to be fixed should be put into a bug tracker or such, where they will get their due attention.

So we can have some general advice: Don’t write comments that repeat code and don’t write things in code that don’t tell you something useful about it.

What makes a good comment?

Good comments. They are somewhat more difficult to give examples on, because good code doesn’t usually need comments!

//Calculate if two circles intersect
$xd = $c2->x - $c1->x;
$yd = $c2->y - $c1->y;
$diameter = $c1->radius + $c2->radius;
$intersection = ($xd*$xd + $yd*$yd) < ($diameter * $diameter);

However, here we do indeed see a good comment.

If the comment wasn’t there, would you know what’s happening? You could probably have guessed from the variable names, but the comment clarifies it even more. Even better, we could put the above code in a method circleIntersection, and make the code self-documenting. Check my article on self-documenting code, as it’s a very powerful technique!

How do you write a good comment like above? I’ll be honest with you: It can be difficult.

There are some things that you can take into account when deciding whether to write a comment:

  • Does this make the intent – in other words, what I meant with this – clear? Research has shown that the intention of the original programmer is the most difficult thing to understand (various books mention this, such as Code Complete)
  • Is this in higher abstraction than the code itself? Comments that are at the same level of abstraction as code are hardly useful and often just end up repeating the code.
  • Am I using a dynamic language? In languages where parameter types etc. aren’t defined in code, defining the type in comments such as JSDoc is useful.
  • Does this explain why I made this specific choice? If you implement a specific algorithm to do something, it might be a good idea to put a comment in why this approach is better than something else.

In addition to above, sometimes you have to write code that’s difficult to understand. A common example is optimized code: Sometimes you just need to optimize a certain routine, and more often than not, highly optimized code can be difficult to read – and that’s a valid place for a comment.

Good comments are difficult but worth it

To sum it up, I think commenting is very useful when done right. It expresses what the original programmer intended, explains things on a higher level so you need to spend less time trying to understand the code, and points out other useful things.

However, good comments can be difficult to write if you’re not used to it. By paying attention to the way you write comments, and actually writing some and perhaps revising them later, will help you become better – same as with most other things related to programming.

Share this:
  1. 32 Responses to “Is commenting your code useless?”

  2. Hi! Thanks for the pingback! :)

    One of the most important things I learned in my experience is to look to comments as an actual smell… maybe they represent something that is better expressed in code?

    For your example, I’d simply take that code and do this:

    function calculateIfTwoCirclesIntersect($c1, $c2){
    $xd = $c2->x - $c1->x;
    $yd = $c2->y - $c1->y;
    $diameter = $c1->radius + $c2->radius;
    $intersection = ($xd*$xd + $yd*$yd) < ($diameter * $diameter);
    return $intersection;

    This imo expresses the code in a much cleaner fashion as I won’t even have to go look at the function to understand what it does… I can just use it. :)

    By James Carr on Oct 15, 2009

  3. I haven’t read TFA. But it’s 100% BS to choose to not write comments.

    I would like to provide a small example here. This is a code snippet from the Zend_Controller_Action_Helper_Url.

        /* Perform helper when called as $this->_helper->url() from an action controller
         * Proxies to {@link simple()}
         * @param  string $action
         * @param  string $controller
         * @param  string $module
         * @param  array  $params
         * @return string
        public function direct($action, $controller = null, $module = null, array $params = null)
            return $this->simple($action, $controller, $module, $params);

    Without the doc block, you would go around checking what the method simple() does, which would lead you to yet another method, another class, etc. Basically, you tread the path of the compiler. What a waste of time.

    It is needless to mention about programs that can generate API documentation from your comments.

    By Sudheer on Oct 15, 2009

  4. I do generally agree that comments are useless for good code, but it does have merit. I see an over abundance of useless comments every day and it drives me mad. However, I believe that the “why” comments are very valuable, especially after revisiting code from ages past.

    As for the example, I believe that generally, James is correct that segmenting out functions is a good thing, but using that to validate not using comments is… meh.

    By Rob on Oct 15, 2009

  5. I do make an exception to my argument… javadocs are okay for public APIs, because it helps a lot. But as long as they aren’t pushing it with essay length descriptions of what they’re doing. 😉

    Robert Martin makes a good case for what represents good and bad comments in the book Clean Code.

    By James Carr on Oct 15, 2009

  6. Using comments like below makes development easier in IDEs like Netbeans and Zend Studio as they can provide you a list of methods and attributes found in the class returned by a method.

    * @return Zend_View_Abstract
    function getView()
    return $this->_view;

    I guess this has to do with how PHP works. With Java you don’t need @return for this purpose.

    By Janimatti Ellonen on Oct 15, 2009

  7. While I generally agree that the use of comments should be minimized, it must be pointed out that comments are not specifically meant solely to relay information to the people you’re working with now: they are notes to the future – a future which may involve no one presently within your team, including you. They may be used by experienced in-house PHP developers, or they may be crucial to contract workers or new employees that come along long after you are gone.

    The goal of comments is to facilitate maintenance *in as little time as possible*, and in pursuit of such a goal, it is entirely appropriate to use them to summarize the behavior of blocks of non-repetitive code if the absence or breakage of any of that code would render it incomplete and/or inoperative. If you can do that clearly through method or function structures, good for you, but in some circumstances (including procedural programming, which is still legal, you know) such comments are massively useful.

    In fact, the wise use of comments encourages a certain amount of organization and forethought within even procedural code – when performing a task, complete it as concisely as possible without mixing it with unrelated processes. If clear commenting is a goal, it can cut down on tangled spaghetti code flow.

    But of course, don’t label the obvious, and do your best to make your code obvious.

    By MonkeyT on Oct 16, 2009

  8. Very good points there, MonkeyT

    By Jani Hartikainen on Oct 16, 2009

  9. I’m definitely on MonkeyT’s side here – in some companies there can be a LOT of contractors coming in for short periods of time, who have to catch up very quickly with what the code’s about.

    Another point is that in JavaScript code, some comments are absolutely essential – to explain a piece of code that might make no sense on first look, but is actually there to get around a particular browser quirk (usually IE).

    By Gilmore on Oct 16, 2009

  10. I think in this debate its important to identify the audience (for lack of a better term) that the code being written will be received by. For instance, if I am writing code that will be modified and maintained only by me then I tend to use comments like $value = 'bad'; //FIX THIS. Its a simple way for me to ‘stick a pin’ in a particular section of the code that I need to review. In a team development setting or when source code will be released to the public however that sort of comment becomes useless.

    @James – I’m sure you’ll agree that calculateIfTwoCirclesIntersect($c1, $c2) is a pretty awkward name for a function. If you and I were working on a project together i’d find that function name rather annoying 😉

    By Samuel Folkes on Oct 17, 2009

  11. Comments are a MUST especially if you are building your own libraries and frameworks.

    By Miroslav Nikolov on Oct 18, 2009

  12. I agree with you Jani, comments really do help a lot as long as they are formatted properly.

    By CodeJustin on Oct 19, 2009

  13. Long story short, no it’s not useless. Of course if you’re collaborating with a lot of people it’s useful, but even if you’re working on a solo project and drop it for 6 months for something else, then come back to it and have no idea what some function did or why you have this file included where it is. Comments just make things easier, that’s why they’re there!

    By Inside the Webb on Oct 19, 2009

  14. Imo (the why type of) comments are definitely useful as is also pointed out in some the comments as well. Two things that spring to mind:

    – The existence of comments doesn’t warrant hard to understand code.

    – When comments get too specific they also tend to get outdated more easily. For instance, specific variable names are mentioned that don’t exist anymore…

    By Tibo Beijen on Oct 19, 2009

  15. I probably will inflame some people now; but I love these simple redundant “set username” comments in source code.


    Because I read normal language much quicker than programming code and I would like to delay having to read (and understand) source code for as long as possible.

    So when trying to figure out what a piece of code is doing, I prefer scanning through some (according to this article probably less valuable) natural language comments than have to interprete each line of source code.

    “set user” simple reads quicker than
    $user->name = ‘Spike Spiegel’;

    Only when I roughly found the block that I’m looking for, I want to involve myself with the actual source code. The comments function like chapter headings.

    So for me: bring out those useless comments please!

    (And BTW, better less useful comments then no comments at all; at least then there is a chance that complex code has been commented as well.)

    By Tbee on Oct 19, 2009

  16. Do you really care what *exactly* happens on each line when just looking for something? Wouldn’t it be more useful to see a higher level comment describing what’s happening on several lines (or a good method name)?

    Then you could just glance over those, instead of having to glance over each of the comments which repeat the code, making you spend less time reading them too.

    By Jani Hartikainen on Oct 19, 2009

  17. Not every line no, but on logical blocks, usually somewhere between 1 and 10 lines. And I really like a comment above each and every block. Even if the block itself is trivial, like initializing variables.

    Furthermore having a comment above each block and method gives a nicely structured view to the source code, especially with color coding editors. It does not become a big black text on a white background, but you get “separators” in green and blue.

    By Tbee on Oct 19, 2009

  18. Having comments do blocks like that is not necessarily a bad thing – As I said, they should describe the block in a higher level than the code itself. However, I do find it somewhat redundant to say “Set defaults” or something if there’s a bunch of variable declarations, even though it is on a higher level =)

    By Jani Hartikainen on Oct 19, 2009

  19. Good post. I responded to another anti-comment post today too.

    By Development Error on Oct 19, 2009

  20. Styles will differ; the main point I want to put forward is that it is faster to read naturaly language comments than to understand source code, and therefor “less meaningful” comments certainly have value.

    And great blog Development Error, I so totally agree! But I did not succeed in adding my “+1” comment.

    By Tbee on Oct 19, 2009

  21. What I see is that Extract Function is not some kind of golden hammer against the so-called “comment antipattern”.

    By Anonymous on Oct 20, 2009

  22. People seem to forget that deciding whether or not to comment can depend heavily on the code’s intended audience.

    An API? Duh, comment. Your web app? Depends: common, reusable code? Comment–it’s a mini-API. Everything else? Depends.

    By Dave on Oct 21, 2009

  23. Both James AND Jani are right!

    This discussion reminds me of the movie Amadeus. It drove Salieri crazy to find Mozart’s original scores. There were no corrections!

    To bring this back to programming, if you can write code like Mozart the first time around. Not too many notes. Not too few notes. Perfect code out of your brain. Then you have little use for notes.

    But if you are not a prodigy, and you code like most people, comments can be quite helpful.

    I wish and hope to write code like Mozart 1 day though!

    By Joe Devon on Dec 1, 2009

  24. Great Mozart analogy, Joe 😀

    By Jani Hartikainen on Dec 1, 2009

  25. I also like the Mozart analogy! Don’t underestimate how easy you can get your code “Mozart” style even if you are a newcomer! Read “clean code” by Robert C Martin!

    By Anders Lindén on Jan 22, 2010

  1. 8 Trackback(s)

  2. Oct 16, 2009: Jani Hartikainen’s Blog: Is commenting your code useless? | Webs Developer
  3. Oct 17, 2009: LimeSpace – IT » Wochenrückblick – Spenden, JQuery, Tutorials und Quellcode
  4. Oct 19, 2009: Random Links #66 | YASDW - yet another software developer weblog
  5. Oct 22, 2009: Revue de presse | Simple Entrepreneur
  6. Nov 19, 2009: Git tips for SVN users | CodeUtopia - The blog of Jani Hartikainen
  7. Feb 14, 2012: No comment(s)…? | That's Mood
  8. Oct 24, 2012: The One True Way syndrome exemplified: the overstated case against code comments
  9. Dec 1, 2014: How to make your code self-documenting? | CodeUtopia - The blog of Jani Hartikainen

Post a Comment

You can use some HTML (a, em, strong, etc.). If you want to post code, use <pre lang="PHP">code here</pre> (you can replace PHP with the language you are posting)