(1) Capture exceptions that should not occur with assertions. Do not confuse the differences between illegal and wrong situations. The latter must exist and be handled.
Not used to check for errors
When programmers start to use assertions, they sometimes mistakenly Use assertions to check for real errors rather than illegal situations. Let's look at the two assertions in strdup:
Char * strdup (char * Str)
{
Char * strnew;
Assert (STR! = NULL );
Strnew = (char *) malloc (strlen (STR) + 1 );
Assert (strnew! = NULL );
Strcpy (strnew, STR );
Return (strnew );
}
The usage of the first assertion is correct because it is used to check the illegal situation that should never occur when the program works normally. The usage of the second assertion is quite different. What it tests is an error, which is an error that will certainly occur in its final product and must be processed.
(2) Use assertions to confirm the function parameters.
(3) When writing a function, you should repeat it and ask yourself: "What assumptions do I plan to make? "Once the assumptions are determined, we need to use assertions to check the assumptions.
(4) In general textbooks, programmers are encouraged to design error-proof programs, but remember that such programming style will conceal errors. When you do error-proof programming, if something "impossible" does happen, you need to use assertions for alarm.