Comments

Professionalism, Craftsmanship, Discipline

I generally see comments in source code for one of three reasons…

  • Copyright Notices
  • API Documentation
  • To make code clear

I have no great issue with the first one. I tend not to do it in my own code but many of the clients I have worked for insist on it and that’s fine.

As for documenting APIs, I understand the reason. However, I’ve seen so many cases where it adds little to your knowledge…

/// <summary>
/// Gets Customer By ID
/// </summary>
/// <param name="id"></param>
/// <returns>Customer</returns>
public Customer GetCustomerById(int id)
{
    return repository.GetCustomerFromBackingStore(id);
}

… How do the comments add any information you don’t get from a well named method with well names parameters? What does the “<returns>” comment tell you that you hadn’t already figured out. To me it adds a lot of noise to the code that makes it more difficult to read.

If I’m actually allowing people to access the source code then I think comments like this serve no purpose. If I’m publishing the code as a package and using the comments to auto-generate documentation, then I can see a purpose. However, my experience of using such documentation is that it usually doesn’t help. It gives you the bare facts with no context and no examples. It’s the last two that really help.

So, if I’m documenting APIs I tend to produce a separate document that focusses on giving context and showing examples. If you’re going to do this then you also have to commit yourself to maintaining the documentation.

I have, on rare occasions, added a comment to make code clear, and I will carry the shame of it forever. What I always try to do is write code that IS clear. If a snippet is really impossible to make clear then extracting it out into a well named method often solves the problem. I will frequently do this, even if the method contains only one line. The extra overhead in the platform making the call is usually utterly insignificant and the extra clarity will save you a lot when someone, maybe you, comes back to the code in a year or so. I think the sole exception to this is where you’re working in a very constrained environment, such as embedded code or in an API where the main constraint really is performance.

I have two reasons for hating comments for clarity so much. One is that all too often, they don’t add much clarity. I’ve lost count of the number of times I’ve scratched my head and thought “What does that actually mean?”.

The killer reason I hate them is that they are a second source of the truth and over time, as code changes, they’re often just plain lies.

Coding Standards