Defensive Programming is a useful auxiliary means to improve software quality technology. Its main idea is that subprograms should not be damaged by passing in error data, even the error data generated by other subprograms. The key to Defensive Programming lies in strict input checks and expected error handling methods. The following describes how to use assertions for defensive programming.
Assertions are generally a routine (routine) or a macro (macros). assertions usually contain two parameters: boolean expressions and messages. The opposite of a Boolean expression is an error. The C standard library provides an Assert macro with only one parameter, for example:
Assert (1 = 0 );
// Note that the Boolean expression is not enclosed by quotation marks.
When you use an Assert macro, you must include the header file cassert or assert. h. The execution result of the preceding statement is that the program stops running and an error message is displayed in the pop-up dialog box.
We can customize the assert macro for two purposes:
1) Add parameters. For example, a message parameter is added to make the assert macro output richer information;
2) modify the behavior content of assert. The assert macro in the C standard library will interrupt the program, so that the program can continue running without interruption or enter the debugging status. In addition, it can also control the message output target, control whether messages are output to the console, text files, or even sent over the network.
The following is a custom assertion implemented by C ++:
# Ifdef _ debug
# Define assert (exp, message)
/
{
/
If (! (Exp ))
/
{/
STD: cout <"assertion failed:" <# exp <"/N"
/
<"Message:" <message <"/N"
/
<"Line:" <__line __< "/N"
/
<"File:" <__file __< "/N ";
/
Exit (exit_failure );/
}/
}
# Else
# Define assert (exp, message)
# Endif
Precautions for using assertions:
1) Use assertions for unexpected errors. Unexpected errors include null pointers, input or output parameter values not in the expected range, and array out-of-bounds;
2) do not put the code to be executed into assertions. Assertions are used for software development and maintenance. Usually they are not included in the release version. Put the code to be run into the assertions, and the code will not be executed in the release version;
3) Use assertions for reliable data from internal systems, instead of for unreliable external data. Use error processing code for unreliable external data.