by Leon Rosenshein

Uncle Bob Says

Though we may try, and try, there are times when we cannot find a way to make the code express our intent; and so we resort, in the end, to a comment. 

We acknowledge that each comment we write is finally due to our failure to express ourselves in code.

    -- Uncle Bob Martin

I sort of disagree. Not with the first part. We should always try to write code that clearly expresses our intent. We use clear names. We break things down into digestible pieces. We try not to rely on side-effects. But sometimes it happens. Too many edge cases, the API that provides the information doesn't match the use case, or maybe it's just that complex. In that case we write comments to help the maintainer understand what is happening.

The second part though, I do disagree with. There are many comments that are not there to make up for failure to express in code, but to reduce cognitive load and to provide information that shouldn't be expressed in code.

Wait, Why do I need information in my code that shouldn't be expressed in the code? The most common thing is "Why". Your code can, and should, be as expressive as possible, and make it clear that you're setting the ignore_duplicates flag on your dB insert sometimes, but not others. What the next person wants to know is why you're setting (or not setting) it. That requires a comment. If the API you're using has some unusual quirks let the maintainer know. Sure, they might be able to find the source for the API and hope it's expressive enough to shed light, but don't subject them to that.

Another good use of a comment would be to explain why you're NOT doing something, If there's an API that appears to do what you want and you choose not to use it, say why. Otherwise the next person to come along will replace that carefully though block of code with a call to the API, and introduce the bug you were trying to avoid.

However, there's a responsibility there as well. You need to make sure that the comment is correct. And stays correct. If the code changes then the comment needs to be evaluated and potentially changed. There are few things in development that will make you want to hunt down the last person to change the code more than relying on a comment that's wrong. It feels even worse when you find out that the last person is you.