More On Assertions
Why Use Assertions?
- The code becomes self-checking.
- The code fails at a location closer to the bug.
- If you put assertions near the interfaces between modules, it makes it easier to assign blame.
- It creates executable documentation about:
- preconditions
- invariants
- postconditions
Assertions In Production Code
Compiler | Assertion Count |
---|---|
GCC | ~9000 |
LLVM | ~13000 |
1/110
Disabling Assertions
Advantages
- Runs faster
- Doesn't abort execution on error
Disadvantages
- If the Assertion accidentally had side-effects, disabling it will change the behavior
- Often better to fail early rather than operate incorrectly
Conclusion
-
It depends on what you want:
- fail early and alert user to problem
- keep going and accept risk of incorrect output
When To Use Assertions
- If you're doing something as critical as the final stages of a rocket landing where aborting could destroy something, it's okay to turn them off.
- Otherwise don't