Principles of using assertions

Source: Internet
Author: User

(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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.