You probably write test programs to verify your implementation. To make sure that bugs are detected as early as possible, it is useful to check preconditions, postconditions and invariants inside your code. Many bugs originate from making the wrong assumption about what conditions that should be true when writing the code. These checks should be done within the implementation of a class, since you do not want to break encapsulation when testing the class. There is a performance cost with having these checks. Normally you want to have checks that are easy to disable after testing is complete. By using macros this is easy to achieve. This chapter is about the consequences of using assert macros.
Rule 11.1 Do not let assertions change the state of the program.
Rec 11.2 Remove all assertions from production code.
Rec 10.7 , if you use C++ to specify classes, assertions can be useful.
Rule 11.1 Do not let assertions change the state of the program.
Assertions are macros since they should be easy to remove from production code. Either you use the assert macro in the standard library or you create your own.
An assertion must not change the state of the program. If it does, the behavior of the program and the state of objects depend on if assertions are enabled or not. This will make it impossible to disable assertions after testing has been done.
#include <assert.h> void check(int answer) { assert(answer == 42); // ... }
Rec 11.2 Remove all assertions from production code.
All assertions should be removed from production code. If they are not, there is a chance that the behavior of the program depends on them. The program will also be faster if unnecessary checks are removed.
Some conditions are not checked by assertions. You should not use assertions to check conditions that should always result in throwing an exception if the check fails. Such exceptions are part of the production code and should not be possible to remove.
// Checked version char& EmcString::at(size_t index) { if (index >= lengthM) { throw EmcLengthError("String::operator[](size_t)"); } return cpM[index]; } // Unchecked version char& EmcString::operator[](size_t index) { assert(index < lengthM); return cpM[index]; }