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
CompilerAssertion 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

From Udacity's Software Testing Unit 1.