Comments Violate DRY

Was talking to a colleague, friend and mentor Troy Bourgeois and in the course of the conversation he said something that struck me. He said writing code comments is just another form of repeating yourself.

I’ve been thinking about this all night. Just like copied code is a symptom of not getting the abstraction right, commenting is a symptom of not getting the code right. Code is supposed to communicate its intent. If it doesn't, then you comment in order to do so.

The real question here is why I feel like I have to add a disclaimer every time I say commenting is a smell? Whether it’s in front of college students, professionals or colleagues. I truly believe that the desire to write a comment is a sign that your code doesn’t communicate effectively, but I guess I fear that people will not strive to write code that doesn’t need comments and rather just omit them.

As Uncle Bob said:
It's not about _omitting_ comments, it's about making them unnecessary.

  1. gravatar

    # by Jeremy Beckham - June 25, 2010 at 8:11 PM

    Comments that say WHAT code does are a smell. That is repeating yourself. Comments that say WHY you did something are NOT repeating yourself.

    For instance, I've run into problems when doing integration work against some REST-ful Java services that required basic HTTP authentication. The .Net HTTP classes have a procedure for setting and using credentials via basic authentication. The classes, however, first try to use no credentials, at which point most servers return a message saying, "Hey, where are your credentials?" and the classes then respond with the set credentials. These services didn't. I had to Base64 encode the credentials, set the HTTP headers manually, and then send the message.

    In this case, I commented the code explaining why it wasn't done using the "normal" method. Anyone coming behind me would probably think they could refactor the code to make it simpler unless they were warned that the integrating system needed it done that way.