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:
Assertions In Production Code
- Runs faster
- Doesn't abort execution on error
- If the Assertion accidentally had side-effects, disabling it will change the behavior
- Often better to fail early rather than operate incorrectly
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