3 ms·
Sometimes code relies on some condition being true, where that condition can be reasoned about by the developer rather than at run time by the program they are
by SulphurCrested 5y ago
Sometimes code relies on some condition being true, where that condition can be reasoned about by the developer rather than at run time by the program they are writing. I don’t think such comments fall cleanly into either the “what” or “why” categories people have mentioned here – perhaps they are “how”.
In mathematical terminology, the condition may depend on some lemma or theorem the programmer proved to themselves when writing the code. (I say “lemma” and “theorem”, but this applies to any kind of complex business logic, or the state of a realtime system, etc.) For a lemma (fancy name for a small theorem), the reasoning can go inline in the code, as a comment. If it’s a theorem, a more substantial thing you proved to yourself when writing the code, it might be better put in a separate document which a comment in the code should point to.
The reasoning you used to show the code works is better off written down for those who follow than forcing them to think through the same logic again. And the act of expressing the logic in a comment will tend to flush out errors in that logic. Those are both good reasons to spend the time writing such comments, unless you don’t care about technical debt.
As a special case, runtime assertions often need a brief comment to explain why they must be true.