Tuesday 29 December 2009

Comments vs Readable Code

There is a widely contested mantra of Extreme Programming that says that comments are superfluous. Inaccurate and often out-of-date meta-information just makes your self-describing code and accompanying tests harder to read and understand.

However the opposite can seem to be true; how often do we try to decipher unpleasant code that has no comments because the mantra said that they were “evil”? It is dogma that leads to this problem.

It is important to remember that “no comments” is mantra not dogma.

Dogma is authoritative and not to be disputed, doubted or diverged from. That doesn’t sound at all agile to me. The word mantra originates in Sanskrit meaning “tool of thinking” or alternatively “liberation of thought”.

Dogma forces you to stick to practices that are believed to be good for you. Mantra can help you to re-evaluate your practices to find those that are actually good for you.

When you come to the point where you feel compelled to write a comment, think hard about whether or not it’s really necessary;

  • Could I convey this comment by renaming a method or variable to something meaningful?
  • Could the accompanying unit test describe the code better?

Can’t think of a good name for a class or method?

Okay, sometimes higher level architectural structures need to be documented, right?…

  • Maybe the class that manages the high-level architectural pattern could be better named?
  • Is a complex high-level architecture really giving you the required benefit if it is not easily understood?

Personally I cannot get to the end of these options without recognising ways of improving my code, although sometimes I’ve added comments to help me understand a large amount of ugly code, prior to refactoring.

The trick is to just keep thinking. Process is never an alternative to thought.