I think it’s pretty interesting that, early in our careers as young budding software engineers, we are told that “write comments to explain why — not what — you are doing”, and I, at least, have never really challenged or evaluated that bit of wisdom. I think it would serve us well to better qualify this by attempting to engineer what a comment should do.

Comments are metadata. They allow a developer to annotate source code directly inline, providing additional information. Most of the time, this information is intended for a human audience. Even when it can also be interpreted by a machine, most of the purposes for which you would do this produce output intended for a human audience. Unless the comment serves a purpose to another program, comments come with a maintenance cost and should offer enough value to justify that cost.

What makes a comment valuable? Comments can contain any information, or no information. They could even improve morale through comic relief or reassurance, if the code is legacy. They could explain the purpose of a method to consumers, or an interface to implementers. They could explain what an esoteric bit of code does, why a particular constant was used, or when the method names do not make it evident, they can clarify what business logic the method is meant to follow. There are even comments that create ascii shapes, borders, and artwork.

Any of those might justify addition of a comment. Any of them may also be inadequate. How do you know what’s worth maintaining?

It sounds stupid, but honestly I think that might be all the analysis that’s necessary. Because if I ask myself directly, “is this comment worth maintaining?” it makes evident what needs to change. Sometimes the comment is too long or poorly written. Sometimes the code needs a rewrite or refactor. Sometimes the comment just adds noise and needs to be deleted. But “is this comment worth maintaining?” is the question that shows me the path. Give it a shot.

Categories: Opinion