A comet will kill you instantly and painlessly. A misleading and outdated comment however can make your life miserable for a while.
A comet will kill you instantly and painlessly. A misleading and outdated comment however can make your life miserable for a while.
The number of times a comment saved my ass, despite being slightly inaccurate: 435
The number of times I struggled to understand what the authors thought when writing "self-documenting" code, because they left no comments: 249579
Draw your own conclusions.
granted, the probability of comet-strike in your lifetime is low, but the severity is off the charts high.
// Do not remove.
// This comment repels comets.I can't count the number of times I've read some code that was very clear that it generally did the correct thing, but clearly wasn't handling some corner case, and it wasn't clear if I had missed something that obviously made the corner case impossible, the author had missed the corner case, or something else was going on.
Or if they did add a similar comment and in the meantime someone implemented it, but didn't remove the comments, how many people will only read the comment and not look at the code?
a future developer potentially forgetting to update a comment is not an excuse to avoid commenting.
The commit message, and unit tests, are where those ideas can be best captured.
I tend to point my team at this as a practice: https://chris.beams.io/posts/git-commit/
This depends a lot on what you mean by "clear" code! You can write higher-level code with abstractions that emphasize the what rather than the how and you can write code that explicitly captures important additional information like invariants. Personally, I've found aiming for that works better than writing code where the "how" is clear at the expense of the "what" so that readers don't lose the forest for the trees.
I am not sure I'm explaining the difference well—it would benefit from examples that I am too tired to provide right now—and documentation is still useful even with higher-level code, but my point is that code absolutely can and should clearly reflect many of the things you would also cover in documentation.
I absolutely agree, but my point was very specific about the "what should" and "why". At best, one could infer some intent from invariants, and hopefully the mapping between the invariants and the requirements document is pretty clear, but comments are still better at explicitly referencing requirements documentation and explaining why the chosen solution is preferable to alternatives.