Categories
Topics

Code Comments Are Useless!

Some years ago I would have refuted above statement with all my might. “No, code comments ensure that you still know what the code is about in two years!” Unfortunately, they won’t.

  • Most likely you will have documented the wrong things. Some constants are explained, maybe a tiny piece of an algorithm but the bigger picture is probably missing. Because there is no commonly accepted place for a description of the bigger picture.
  • Code comments will not be maintained. You say, they will but they really won’t. Recently at work I had to touch a class called KafkaTrackingEventWriter. Apparently this class writes TrackingEvents to Kafka. Its javadoc comment began with “ProfilingEventLogger which…”. The signature of the method doing the work was “void write(UserInteractionResult).” What was your point again, comment?
  • Code comments will not be maintained. This warrants a second entry in this list because sometimes the comments are not clearly recognizable as wrong or outdated. Instead, they look like that are still valid but they introduce (or omit) subtle details about what really happens, leading to hard-to-trace bugs and many wasted hours.
  • Most code comments really are useless, as in: they do not add any value to the source code whatsoever. How many times have you seen a constructor commented with “creates a new thingamajing” or “constructor?” Do you really need a javadoc comment to know that a “Thing getThing()” method returns a Thing? I have seen them more than just a few times and frankly, when I see one of those now, I simply delete the comments.

So, recap time! What is there to use instead of code comments? Source code, of course. Method signatures can be way more expressive than comments, and contrary to comments they will always be true.

Instead of

/**
* Returns an address for the user, or null if no address is found.
* @param user The user
*/
public String getAddress(String user) { … }

use

public Optional<Address> getAddress(User user) { … }

Even though the second method has no comments, it is a lot clearer what this method actually does.