Snippet · Writing & changing code
Comment the why, not the what
Most comments restate the code. The useful ones can't be inferred.
Here's my code: <paste> Two passes: 1. Delete comments that just restate what the next line does. List what you removed. 2. Add comments only where something can't be inferred from the code: a non-obvious constraint, why the obvious approach doesn't work here, a workaround for an external bug, a magic number's origin, an ordering that matters. If you don't know why something is the way it is, ask me rather than inventing a reason. A wrong "why" comment is worse than none.
Wrong explanatory comments are actively harmful — people trust them and stop reading the code. Better to leave a question than a guess.