Thursday, November 3, 2011

Comments considered harmful

At school, I was taught to comment my programs well. Today, I wonder why I should.

Every comment relating to the code itself is redundant. Redundancy creates inconsistencies, and inconsistencies are a serious threat to code quality. So I prefer not to comment.

"Hey, come on! How do you expect anybody to understand your program if you don't comment it?" I hear being shouted at me. I will ask the opposite question: Why should I write such a lousy program that it needs comments to be understood?

I worked in a group where the coding guidelines said: Comment every class, comment every method. I refused. I mean, as an example, look at this getter, generated by the Refactor -> Encapsulate Fields... operation of NetBeans:

    private String name;
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

What does that comment add that I did not already learn from the method name? So rather than commenting a method, I prefer to use the comment,  kind of, as the method name. That guarantees consistency and also propagates the "commented" intent to every place the method name is referred to. Far superior to a localized comment!

Martin Fowler once said: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." I strive to be one of them.