Why I don’t write code comments

These days I was configuring some personal projects on ohloh and one thing called my attention. Ohloh showed the message “very few source code comments” in all my projects.

This is no surprise to me. I really don’t like to write source code comments. Why? Because if my code isn’t clear and easy enough for one to read and easily understand, I need to refactor. Many times I ask friends to take a look at code snippets and check if they understand. When they don’t, the method is usually too big or the variable/method names are not clear enough, and then I refactor to make it better to understand.

One example that I love (and use in many presentations) is the code to send e-mails using Java Mail API. The code would be something like this (from Java World tutorial):

// create some properties and get the default Session
Properties props = new Properties();
props.put("mail.smtp.host", _smtpHost);
Session session = Session.getDefaultInstance(props, null);
 
// create a message
Address replyToList[] = { new InternetAddress(replyTo) };
Message newMessage = new MimeMessage(session);
if (_fromName != null)
    newMessage.setFrom(new InternetAddress(from,
        _fromName + " on behalf of " + replyTo));
else
    newMessage.setFrom(new InternetAddress(from));
    newMessage.setReplyTo(replyToList);
    newMessage.setRecipients(Message.RecipientType.BCC, 
            _toList);
    newMessage.setSubject(subject);
    newMessage.setSentDate(sentDate);
 
// send newMessage
Transport transport = session.getTransport(SMTP_MAIL);
transport.connect(_smtpHost, _user, _password);
transport.sendMessage(newMessage, _toList);

I know that this is just an example but you know that it’s not difficult to find monsters like this one in production code.

This code is so difficult to read that the programmer had to say what he was doing, otherwise nobody would understand its purpose. There is a lot of infrastructure and business code together resulting on a huge abstraction leak.

Now take a look at the following code (from Fluent Mail API) and tell me how many seconds do you need to understand what the code does:

new EmailMessage()
    .from("demo@guilhermechapiewski.com")
    .to("destination@address.com")
    .withSubject("Fluent Mail API")
    .withBody("Demo message")
    .send();

This is an extreme example, of course. Maybe you will not write Fluent Interfaces for every little thing you need in your code, but if you add just a little bit of organization (using a better abstraction) it will already improve code readability:

class Email {
    public Email(String from, String to, ...) { ... }
    public void setFrom(String from) { ... }
    public void setTo(String to) { ... }
    public void send() {
        // put your complicated Java Mail code here
    }
}

Just by encapsulating the code in an abstraction that makes sense the WTF effect will be sensibly reduced. The programmers can now at least assume that the code sends e-mail messages since it’s included in a class called “Email”.

And that’s the point. When I create a culture of prohibiting myself from writing code comments, I’m obligating me to write easy, maintainable and understandable code.

That’s very extreme, I know, but the results of this approach are awesome.

Tags: , , , , ,

27 Responses to “Why I don’t write code comments”

  1. Diogo Santos says:

    This is what I think about code comments!!

  2. Marcos Sousa says:

    Chapiewski,

    I think programmers comments their codes because they usually violate the SRP (Single Responsibility Principle) and, as you said, they give unclean variable/method names.

    This problem becomes more stronger when the system is highly coupled or is based on BOLOVO frameworks.

    In my opinion, pair programming and TDD approaches help the programmers to write maintainable and understandable code.

  3. Alan Kelon says:

    Aren’t you missing the else brackets?

  4. Rafael says:

    I like so much this subject.
    Of course you know this, but for the readers, there is a awesome presentation made by Shoes using a same example:
    http://fragmental.tw/2009/03/12/expessive-design-slides/
    []‘s

  5. Alberto Leal says:

    Gc,
    I think not write code comments is an exaggeration. Logical that, before writing any comment, try to refactor and make it useless. A comment is useful when you don´t have much knowledge about that part of the application. Thus it´s great to leave a comment, then the next programmer can understand what/why you´ve done that.

    Cheers,
    Alberto

    • @Alberto

      Gonna repeat it:

      “When I create a culture of prohibiting myself from writing code comments, I’m obligating me to write easy, maintainable and understandable code.”

      Don’t write code comments. If you want the next programmer to understand your code, write good, simple and understandable code! It’s much more valuable than any comment you will ever write!!! :)

      BUT, I’m not saying that you shouldn’t write any documentation at all. Architecture diagrams are sometimes very useful to talk about the system and sometimes complex things need to be explained in some way. Although – I insist – you should worry about keeping your software very simple, with a good naming policy, with good abstractions, with separation of responsibilities between objects and very very well tested (that is proven to be good way of documentation).

  6. Alberto Leal says:

    Gc, I agree with you. Every programmer MUST write simple and comprehensive code. But, sometimes, when you don´t have sure about what to do, and there is nobody close to you to help you, it´s a good ideia write some comments. In the future, those comments you inserted in your code, may be excluded from your code.

    Take a look at what Martin Fowler says about it, and see what I mean:

    “When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluos.
    A good time to use a comment is when you don´t know what to do. In addition to describing what is going on, comments can indicate areas in which you aren´t sure. A comment is a good place to say why you did somenthing. This kind of information helps future modifiers, especially forgetful ones.”

    • @Alberto

      Sometimes, specially when you work with lots of teams/people, this just don’t work.

      In my experience, when you check in code that is unfinished, the comments generate more stress and doubt than any other thing. We just had a similar problem last week here at my team when one programmer commited and pushed code to our master branch with 3 lines of comments explaining his frustrations, but none of them helped the next programmer to do something about it. In fact the comments generated even more doubt and we inevitably had to stop and discuss immediately about the code and give a definitive solution to the problem.

      That’s why I really think that code comments are a big bad smell and should be avoided.

  7. Rafael Ponte says:

    Great post GC!

    When a developer writes a clean, simple and expressive code all the team gains with that! Mainly in the maintaining aspect on software!

    I always try to write expressive and legible code when I program. So, I always try to avoid unneeded comments on code.

    I think it’s not necessary a Fluent Interface (because sometimes is really expensive write one), just a legible code is good enough the most of the time.

  8. André Pinto says:

    Code comments only exist because written code isn’t clear enough… And I’m also sure that the comments are almost never updated with new changes… So we have a lot of useless comments.
    At the company I work for, we must avoid writing comments… We must write clear and understandable code, since the code is reviewed by other developers…

  9. I think this problem arises when people don’t know how to factor concerns (which are not coupled together) in objects collaborating to realize some purpose.

    So, this kind of code ends up being messy, rot and very difficult to maintain.

    A good design approach talks about objects with one responsability and clear method names indicating their purpose, with indirections isolating things that change freqüently from things that stay the same.

  10. Carlos says:

    It seems you are suggesting that expressivity in code must be delivered since the first attempt. I beg to disagree, obviously it depends on the length of iterations because expressivity means rewriting the same code several times, but generally in agile projects refactoring is an iterative and incremental activity.

    Comments can be useful to handle this transient situation if, as any other tool, used correctly.

    • @Carlos

      This is a common misconception about Agile. :)

      Although you must build features and functionalities iteratively and incrementally, the QUALITY have to be built in since the very first moment!

      You will not write crappy code to be rewritten from time to time, you will write high quality code that will be refactored every time. You have to write high quality and well tested code so you can quickly refactor your software to accommodate changes – that’s Agile.

      I insist that comments can and should be avoided, but, as any other Agile rule, this is not a silver bullet.

  11. Carlos says:

    I agree 100%! Quality should be a concern since the first moment…

    but I think lack of expressivity (or expressiveness?) in code does not necessarily make it crappy code.

  12. Lucas Oleiro says:

    To support your post, there’s a good book about the same subject with a lot of other arguments:

    http://www.infoq.com/articles/clean-code-book-review

  13. [...] “Radical” e “extremo” são palavras que têm uma conotação muito negativa, mas ser radical ou extremo pode ser muito útil quando se tem um propósito como esse (ou então para se fazer uma abordagem como a que eu postei sobre porque eu não gosto de escrever comentários no código). [...]

  14. [...] “Radical” e “extremo” são palavras que têm uma conotação muito negativa, mas ser radical ou extremo pode ser muito útil quando se tem um propósito como esse (ou então para se fazer uma abordagem como a que eu postei sobre porque eu não gosto de escrever comentários no código). [...]

  15. Anderson says:

    How can I use the “no-reply”?

    I’ve expected a “.replyTo(…)” !

  16. [...] “Radical” e “extremo” são palavras que têm uma conotação muito negativa, mas ser radical ou extremo pode ser muito útil quando se tem um propósito como esse (ou então para se fazer uma abordagem como a que eu postei sobre porque eu não gosto de escrever comentários no código). [...]

  17. Tomamais says:

    You always should “talk” with your code, but talk in human languange, as posible it is. In simple cases as a mail sender, its very easy to use this philosophy, but not when we need a complex business logic. Can you imagine a method like “Order.IsReadyToBeApprovedByAccountManager()”?

    When language code is not sufficient to be clear by itsel, the best way is put comments around code. But not a comment like a book history ok? Leave this do Word Documents.

    Sorry for my english

    • Your “IsReadyToBeApprovedByAccountManager” example is really ugly, but take a look at the following examples:

      Order order = anOrder().from(aCustomer().with(anAddress().withNoPostcode())).build();

      (from Nat Pryce blog)

      describe("Jasmine", function() {
        it("makes testing JavaScript awesome!", function() {
          expect(yourCode).toBeLotsBetter();
        });
      });

      (from Jasmine project)

      Take a look also at this article I wrote some years ago about a refactoring to use Fluent Intrefaces (in Portuguese).

      The effort to make your code readable and easy is always worthwhile.

      You can write good, solid, semantic, easy-to-understand, readable, clean code, OR you can continue writing code like this (and you will need tons of documentation, of course): http://vimeo.com/9981123

  18. [...] to try to keep yourself from adding TODO comments to your source code in the first place (in fact, this applies to code comments in general); but, if you do, make sure you don’t forget about them (Eclipse has a “Tasks [...]

  19. [...] precisam ser documentados porque eles são desnecessariamente complexos. Sempre que possível prefira refatorar o código para ele ficar mais fácil de entender ao invés de escrever comentário… (até porque muitas vezes o código muda e o comentário fica lá desatualizado, e isso acaba mais [...]

  20. [...] precisam ser documentados porque eles são desnecessariamente complexos. Sempre que possível prefira refatorar o código para ele ficar mais fácil de entender ao invés de escrever comentário… (até porque muitas vezes o código muda e o comentário fica lá desatualizado, e isso acaba mais [...]

Leave a Reply