Quality over quantity: The right way to comment code

Have you ever in your career seen a code file that was loaded with comments, but when you actually read them, they were largely useless? I have.

Ones where the author is just stating obvious things like what a loop is, translating a simple if-statement into English for some reason, or apologizing for code that sucks without saying why it sucks.

So let’s talk about how to leave quality code comments.

Quality code comments state your intentions.

Knowing what the previous coder meant to do is one of the most valuable safeguards for maintainability.
You can’t fix bugs in a system whose intended behavior is a mystery to you.

If I don’t know what it’s supposed to do, how can I tell why it’s broken?

Quality comments state your assumptions.

In the same way that stating your intentions lets the next coder know how to reconcile what you meant and what you actually did, stating your assumptions helps the next coder reconcile your assumptions with reality.

You’re going to make some bad assumptions. Write them down.

Quality comments state what you’d like to do differently in an ideal application.

Writing // this is a pile of crap, and i'm sorry is not helpful. Provide guidance for improvement. What would be better? What are some things outside your expertise that you’ve heard could help?

Most of the time, ideal solutions are not a realistic goal, and you’re not going to write your favorite code. But maybe someday you or someone else will have a pragmatic reason to reach for the ideal.

Quality comments reference source material.

If you did a lot of research and reading to get to the solution that you wrote, it would be a good idea to write that down. The next person to work on this code shouldn’t have to go hunting to find the information that you already located.

Be pretty liberal in applying this technique.

Even if you think that anyone could find the same things you found, the fact that you’ve already curated the reading material down to what actually matters is valuable. Pass that value on.

But never use comments as a substitute for good code.

Comments are a complement to, not a replacement for, good code. But just because code is good does not make it easy to understand. After all, some things are just hard.

Good comments make those things easier on the next person.

I’m sure there are plenty of other opinions on what makes a good comment, so if you have one please feel free to… uh… leave a comment.

More Posts by Joel Wietelmann: