More On Assertions

Why Use Assertions?

  1. The code becomes self-checking.
  2. The code fails at a location closer to the bug.
  3. If you put assertions near the interfaces between modules, it makes it easier to assign blame.
  4. It creates executable documentation about:
    • preconditions
    • invariants
    • postconditions

Assertions In Production Code

Production Compilers
Compiler Assertion Count
GCC ~9000
LLVM ~13000
Total lines of code for LLVM: ~1,400,000. Ratio for LLVM of Assertions to Code:
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
From Udacity's Software Testing Unit 1.