Once Again: Comments In Code Aren’t Necessarily Bad

33 commentsWritten on August 18th, 2010 by
Categories: Code Quality, Opinions

I happened to come across some blog posts and tweets that once again mentioned how evil it is to use comments in code. Some people still like to advocate the "if you need comments, your code sucks!" sentiment. As is often the case with this kind of statement, the only correct (or dare i say realistic) point of view is: it depends!

I generally agree that you should strive to avoid comments in code. That is, you should write your code in a way that doesn't require comments for the reader to easily understand and grasp what the code is doing. However... there are situations where comments are helpful (or even required), since you simply can't write everything in such a manner that it doesn't require any comments.

To back up my point, i'd like to point you to this challenge i posted over a year ago. That code is clean. But pretty much everyone could use some comments to understand why that certain approach was necessary since it's just not that obvious when focusing solely on the code. That code applies a certain pattern which isn't well known, but there is a very specific reason why the pattern is needed. And i still believe that most developers need comments to understand it properly. That's not to say that the guy who wrote it (which happened to be me) is better than those who're going to have to maintain it. Hell, i wrote the code, and i would certainly be glad to see some comments in that code if i had to make a change 6 months after the fact.

The key thing to remember is this: don't blindly follow what the books and/or the 'legends' say. If you need to write some code in a very non-obvious way, then you could really make things easier for those who need to maintain it (which could very well be you, btw) by including some comments to explain why a certain solution/pattern was chosen. There are some details you simply can't show through good naming practices or clean code in general... some things simply need to be explained and it's quite possible that a WHY comment or two benefits not only you but whoever is going to read the code more than some kind of excessive and futile exercise in making it as easy to understand as possible without comments ever will be.

In short, strive to avoid the need to write comments by writing clean code. But don't be afraid to use comments wisely either when clean code simply doesn't cut it. There's nothing wrong with that. After all, we don't all have the luxury to restrict our efforts to contrived examples.

  • http://ackenpacken.blogspot.com/ ackenpacken

    I think the whole comment fuzz lately is trying to do just that. Only it goes back and forth between two extremes gradually settling in the middle. The other day I caught a colleague using a tool to auto generate comments because comments was required for all public and protected methods in the project he’s working on. After seeing that I really felt like telling the people behind that “IF I EVER SEE YOU WRITE A COMMENT AGAIN I’LL PUT A FOOT IN YOUR ***”. But like you say, somewhere in the middle.

  • http://davybrion.com Davy Brion

    Well yeah, comments like the ones you mention don’t offer any benefit at all and they should never be written (or even generated)

    but my point is that there definitely are some cases where comments are justified/required and it would truly be a shame if the developer didn’t include them because “Uncle Bob said comments indicate failure!”. Guess what: sometimes Uncle Bob is wrong (see the whole DI/IOC discussion from a couple of months ago). And there’s nothing wrong with being wrong, you just have to accept the fact it happens from time to time.

  • Alex Simkin

    How about this?

    private void UseCopyOnWriteToModifyClients(Action<List> action)
    {
    lock (monitor)
    {
    var clientList = new List(clients);
    action(clientList);
    clients = clientList;
    }
    }

    private void AddClientToRegisteredClients(IClientProxy client)
    {
    UseCopyOnWriteToModifyClients(c => c.Add(client));
    }

    private void RemoveClientFromRegisteredClients(IClientProxy client)
    {
    UseCopyOnWriteToModifyClients(c=>c.Remove(client));
    }

    :)

  • http://ackenpacken.blogspot.com/ ackenpacken

    Like he says “comments indicate failure”. Until written in a self explaining way it’s considered a failure but no code base is ever failure free. So the way I interpret him comments should only be used in those parts of your code where you have failed to express it’s intent clearly.
    I think both of you are saying the same thing phrased differently.

  • Koen

    My experience is that whenever you feel that you need to write comments (or feel that comments are missing) you’re dealing with rather technical code, meaning a component that you are steering or anything, like streaming, messaging, encryption, broadcasting in your example,…

    On the opposite I think that if you feel like you need to write a comment in non-technical code (good ol’ business logic), then you probably need to reconsider your existing code first and see if you’re acutally done refactoring…

  • http://davybrion.com Davy Brion

    @Alex

    while that does have a nicer syntax, it still doesn’t explain why copy-on-write is important in that scenario :)

    you could still read that code and think “oh great, another YAGNI/KISS violation”… which is no offense to your code of course, but you know what i mean

  • http://davybrion.com Davy Brion

    @Koen

    now that is a distinction i can agree with… in fact, i wish i had thought of it much sooner :)

  • Bob

    “I generally agree that you should strive to avoid comments in code.”

    You’re an idiot. Nuff said.

  • http://davybrion.com Davy Brion

    @Bob

    you’re the one spending time on this idiot… isn’t that worse?

  • Alex Simkin

    @Davy

    UseCopyOnWriteToModifyClientsBecauseWeNeedToBeAbleToLoopThroughTheClientsWhileWeAreDoingThis

  • http://davybrion.com Davy Brion

    @Alex

    lol… ok seriously now, what is the difference between that and a comment, other than not having to use // ? Seriously though, it’s virtually the same, except that a proper WHY comment can always give more context than a huge method name can

  • Alex Simkin

    @Davy,

    Because comments use to get out of sync with the code.

  • http://davybrion.com Davy Brion

    @Alex

    ah, but that’s just a matter of discipline… which, as i’m sure you’ll agree with, is one of the most important characteristics of a good developer

  • Alex Simkin

    Good developers do not need “best practices” they use “gut feeling”. All these “best practices” are created in an attempt to make mediocre developer to produce a better code.

  • http://davybrion.com Davy Brion

    @Alex

    well… that’s a pretty bold statement :)

    i’m not even gonna touch that one :p

  • http://annalear.ca Anna Lear

    Because comments use to get out of sync with the code.

    @Alex: and if someone changes the guts of the method without renaming it, you have the exact same problem on your hands. It still comes down to developer’s discipline.

  • http://davybrion.com Davy Brion

    @Anna

    nice one! :p

  • http://irascianwork.blogspot.com Ian Smith

    I recently went to an Uncle Bob talk where this whole “don’t do comments” nonsense was trotted out. What was scary was overhearing some of the more gullible starry-eyed younger developers in the break saying how pleased they were about this advice from the guru because they’d never liked writing comments.

    Those of us working in the real world often have to work with external systems we can’t refactor or fix. Obscure rules (essentially arising from crap data) come into play and if you don’t know the reason for the rule looking at the computer logic that deals with it is NOT going to explain it to you – it’s just going to make you think “The guy who wrote this was dumb – I’ll just fix this up” and then 2 months down the road it surfaces as a real production problem. Been there done that too many times in the past. Comments help explain the code and in an agile world where the likes of Uncle Bob et al are promoting lean and mean (ie documentation was on a whiteboard someone forgot to copy or on an unmaintained out-of-date wiki somewhere and the original staff have all left to find a company that ‘does agile properly like Uncle Bob told us to do it’ or whatever) those comments can become essential.

  • http://www.timua.com Tiendq

    I have no reason to not write comment in my code, surely after months it is easier for me to read the comment first to know what code does instead of try to understand the code itself. Of course, comment is complement to code, not a copy of code.

  • Oleg

    Ian, 100% agreed. Self-explanatory code is ideal. And as any ideal sometimes it is just not reachable.

  • http://bjarte.com Bjarte

    The problem with “it depends” is that the expression often takes away the punch of your message. Sometimes it’s often better to get your message out there and leave the edge cases for an in-depth article or something of the kind.

    One thing I have noticed lately is that comments often make more sense in dynamically typed or weakly typed languages. Especially if you go crazy with things like mixins in Ruby.

    Comments has its place in statically typed languages as well. Typically when you are documenting a public API or working with some crazy code you have no control over. In my own code I usually find a good way to express developer intent without comments. The intent expressed in code does not wither.

    Statically typed languages also have the benefit of static analysis which removes most of the need for comments.

  • http://davybrion.com Davy Brion

    @Ian

    very nicely put :)

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #668

  • http://priscimon.com/blog Eddy Young

    I had to write a comment once in my previous job, as a warning to others who follow.

    “ABANDON ALL HOPE YE WHO ENTER HERE.”

    Eddy.

  • http://davybrion.com Davy Brion

    @Eddy

    now that code is something i’d love to see :p

  • http://blogs.lessthandot.com chrissie1

    I don’t use comments very much but I don’t mind if people do use comments in their code, I’m actually very glad MS did use the comments from time to time. And yes they could get out of sync but then you just proved you are not a professional if you let them go out of sync. But I guess it all has to do with the quality of your code, if you have very short methods using all the good practices you will probably not feel the need to explain yourself. But if you spaghetti code then you will need a whole book to explain what you are doing and where.

    I would never look down on anybody because they use comments. I would be more worried if they didn’t have tests or had methods 3000 lines long.

  • http://priscimon.com/blog Eddy Young

    @Davy

    It was code to do will and estate projections based on inheritance tax rules. Without a single comment.

    Eddy.

  • Paul Cox

    Wouldn’t the comments be duplicated via code in the unit tests that show why you are using copy-on-write?

    I’d also say that comments would only help if someone needed to change this code, and looking at it briefly for this specific case, I can’t see why it would need to change.

  • http://davybrion.com Davy Brion

    @Paul

    you can find (some of) the tests here: http://davybrion.com/blog/2009/02/the-tests-for-the-readable-code-challenge/

    i really don’t think you can write those tests in a way that completely removes the necessity of the comments… the comments are read very easily and it doesn’t take any time. Understanding the tests will take more time than reading the comments however.

  • Alex Simkin

    Real comment from the code that we are re-engineering now:

    I set DueDate to NULL, otherwise background process (which I cannot control) will send this order to the warehouse floor for fulfillment before payment is confirmed. I stash due date in the customer fax number because I cannot modify db schema at this stage.

    Note to myself or any unfortunate soul who comes after me: do not forget to copy date back after payment batch is confirmed.

  • http://www.buckaroocoder.wordpress.com Chuck

    I am simply happy to get either an appropriate comment, or a nicely named variable/function.

  • Pingback: Anna Aleriel Lear » Are Comments Evil?

  • Pingback: code bullets