This should go without saying, but it doesn’t. We should treat a comment as though it’s a danger signal. A comment is either an admission of failure, or a warning about the unexpected.
In Talking Around Your Docs, I looked at how it used to be fashionable to explain every line of code.
Maybe if we defaulted comments to flashing red, people would use them more wisely!
Documentation is Good
API documentation, read inline with the code, and published out to API sites, is good! It’s versioned with the code; it’s right there; it explains the semantics around using that code. That’s got to be useful, right?
What the HELL is THIS!?
The above is an example of a nervous tic. Filling a comment because we somehow need to sacrifice some screen space to the gods.
Would it be better like this?
No. Because the variable name should spell out what’s going on.
A lot of comments we write are no better than this!
When to write line by line comments
When I’m writing in an unfamiliar, or non human readable language, then I may choose to explain what the code is doing for the unwary.
This is probably in the category of an admission of failure. The truth is that I don’t really speak
The above is valid code, but perhaps a little more obscure than the equivalent well-named methods in Java… and perhaps it would be overwrought to use explanatory functions, especially where the filter is concerned.
Can I be forgiven for:
Maybe the above is helpful in terms of comment, but it’s no way to live your life.
Code is a language and should express itself. Sometimes our books have footnotes or asides in them to explain the text, and perhaps that’s useful occasionally in code. But it can’t be the norm.
In rare cases, it may be forgiven though… unless it’s saying nothing.