Did I get your attention? Good.

To many of my fellow programmers what I am about to say  is second nature. However, taking a recent discussion into consideration it is not second nature to everybody.

fight460

I don’t really think my point of view is very controversial. It basically goes like this:

Write comments in your code if  it adds value

Obviously this is a very vague guideline. When does a comment really add value?

Comments on classes

In well written object oriented software your objects play one or more roles. I find it valuable to add a comment to the class declaration explaining the objects role in the system. This helps you see the big picture, which usually cannot be described by a simple class name. Sometimes it can.

It’s easier to explain my attitude towards writing comments by going thru the cases where I don’t write comments, as opposed to talking about the ones where I do.

Comments on and inside methods

In my opinion you should usually not comment your methods and the code inside them. Public APIs is an exception.

In well written code a method should only have one or two responsibilities. This means that by carefully selecting a method name you can give the reader a good idea of what is going on inside the method. Now, obviously you cannot explain the nitty gritty details, but that is what code is for. If you want the details, you should read the code. Method level comments cannot really add value. Putting a short description of what the method does in the comment is redundant because the method name is already doing this. Putting details in the comment gives you a maintenance hell when you need to keep the comment in sync with your code. If you want the details you better read the code.

Inside a method your often feel the urge to insert some comments to make the code more readable. Why don’t you just make the actual code readable instead? If you have a section of code that is doing some complicated calculation you can always put the calculation in its own method and give that method a meaningful name. Problem fixed.

Obviously there are some exceptions to my above comments. They are few. If you find yourself commenting a method or code inside a method usually it is a problem with your code. Comments are often a code smell.

Another problem with comments is the fact that you need to maintain them as you change your code. Up to date comments is not a big problem. Out of date comments is a big one.

When it comes to the title of this post, it’s not completely accurate.Today I’m pretending I’m running a tabloid.

(Please see my comments in the context of good old OOD. They might not be totally suitable for functional programming)

F Share