Aussie AI
Dynamic Self-Testing Code
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Dynamic Self-Testing Code
The main disadvantage of assertions and other self-testing code is their inefficiency, especially if they are left in production code. Most assertions are a simple inexpensive conditional test, but those that are more costly can be implemented using a different macro, say, “expensive_assert”, which is enabled only in debug mode.
The simple idea is run-time option to enable debugging mode, which will set a particular global variable, with a clever name such as “ydebug.” All of the expensive assertions, self-testing functions, and debugging output functions will test this global variable before calling the appropriate function, so that the only loss in efficiency for the end user is a single conditional test.
For example, assuming “ydebug” is the Boolean global variable (a fancier implementation might allow it to be a debugging level), the expensive assertions, self-testing functions and debug output statements would be implemented with ideas such as:
extern bool ydebug; #define expensive_assert(cond) ( ydebug? assert(cond) : (void)0) #define self_test_fn(x) ( ydebug? real_test_fn(x) : (void)0) #define DPRINTF (!ydebug)? (void)0 : debug_printfIn this way, the global variable debug is tested before the function call, and this Boolean test is the only cost for the end user. The only difficult part of the above method is the definition of the debugging output statement DPRINTF; the above macro declaration assumes that DPRINTF accepts a variable number of arguments.
Note that larger blocks of self-testing code that are not implemented as functions could simply be placed inside an if statement:
if (ydebug) { // ... Self-testing code }
The use of “ydebug” could also be hidden behind a macro so as to make changes to it easier. One possible style is block-like:
#define YSELF_TEST if(!ydebug){} else YSELF_TEST { // ... Self-testing code }
Various other ways to use self-testing code and debug trace statements are examined in the debugging chapter.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |