3 ms·
Some code needs "why" comments, and other code just needs "what" comments (unless it's written in a clear, high level language; then not). "Why" comments need
by kazinator 3y ago
Some code needs "why" comments, and other code just needs "what" comments (unless it's written in a clear, high level language; then not).
"Why" comments need to go onto code that make some kind of arbitrary decision. Or code which is integrated with processes that are happening elsewhere and has to behave in a way that complements those behaviors. Otherwise the reader would have to read that code together with all those other pieces (or specifications) in order to understand it. Code that is written in a certain way (particularly, an unusual way) for some reason that is not obvious deserves a "why" comment. E.g. "due to a compiler/library bug [give specific version info], we cannot just do this: ...".
Code that doesn't make arbitrary decisions or integrate with things elsewhere, or make unusual coding decision for reasons, often doesn't require "why" comments.
The author of the article hastened to add:
> And when you do need [comments], it’s often when you’re doing a very specific or obscure thing that requires context to understand. It’s clear from the code why you need a comment in that case.
It's clear from the code why you need a comment, because it's a "why" comment.