Note: how to make good use of assert and see what the classic saying is

Source: Internet
Author: User

I have been engaged in software development for almost five years. I often see that I have not properly used assertions when I read the code, and whenever I raise a topic about assertions, it seems that it will always be controversial.

This is not a very attractive topic, because many famous books have already been elaborated on and widely spread on the Internet. The book is as follows.

I recommend the use of assertions in C language interface and implementation and programming essence.

 

Code Daquan

5.6.l Use assertions

Assertion is a function or macro command that will protest loudly when the assumption is incorrect. Assertions can be used to verify the assumptions made in the program and eliminate unexpected situations. In the development phase, assertions can eliminate conflicting assumptions, and eliminate negative values of input subprograms. During the maintenance phase, it can be indicated whether the change affects other parts of the program. If you use a Preprocessing Program to process assertions in the development phase, it is very easy to remove the assertions in the final code. However, you should avoid using executable code in assertions and put the executable code into assertions because it will not be compiled when the assertions are closed.

 

5.7 subroutine Parameters

Description of parameter interface assumptions. If the data passed into the subroutine has some characteristics, You need to describe this assumption. Note this assumption both in the subroutine and in the place where the program is called. If assertions can be placed in the Code, the effect is better than comments.

 

Programming Pearl

5.3 asserted Art

Some projects use a pre-processor to define assertions, so the assertions can be processed during the compilation phase without causing additional runtime overhead. On the other hand, Tony Hoare has noticed that when using assertions during testing, programmers who close assertions during product release are like wearing a life jacket during Shore drills, but the sailors who took off their life jacket in the Lower sea.

 

Clean code

It's good documentation, but it doesn't solve the problem. If someone passes null, We'll

Still have a runtime error.

(Note: assertions can also be annotated, but they do not solve the problem .)

 

C language interface and implementation David R. Hanson

2.4 responsibility of the customer for calling the program

(To be added: This section describes the application of assertions from the interface design perspective. It is the clearest explanation I have ever seen !)

Chapter 4 Exceptions and assertions

(Omitted)

 

Writing clean code

 

2nd
Chapter design and use assertions

It is good to use the Compilation Program to automatically check for errors, but I dare say that as long as you observe the obvious errors in the project,

Only a small part of the Compilation Program is found. No algorithm error can be found in the compiled program.

Prove the assumptions made by programmers. Generally, the compiler cannot check whether the passed parameters are valid.

 

Key points:

 

@ Use assertions to confirm the function parameters.

Use assertions to confirm the parameters of the function, and trigger an alarm to the programmer when the programmer uses undefined features. The stricter the function definition, the easier it is to confirm its parameters.

 

@ When writing a function, you should repeat it and ask yourself: "What assumptions do I plan to make ?" Once confirmed

Use assertions to test the assumptions, or rewrite the Code to remove the corresponding assumptions.

. In addition, you should also ask: "What are the most likely errors in this program, how can we automatically find out

Error ?" Efforts should be made to compile a test program that can detect errors as soon as possible.

 

@ Delete undefined features from the program or use assertions in the program to check for illegal use of the undefined features.

 

If the reader stops reading ANSI C
In the definition of the memcpy function, you will see the last line saying: "If a copy is made between objects with overlapping buckets, the result is not defined ". Some programmers are deliberately using undefined features, but we should not follow suit. Non-defined features are equivalent to illegal features, so we need to use assertions to check them.

 

So from now on, you should stop to see if there are any undefined features in the program. If

Undefined features should be removed from the corresponding design, or the corresponding assertions should be included in the program, so that users can send notifications to programmers when using undefined features.

 

@ Add annotations to unclear assertions.

This is like when a person passes through the forest and sees

The big brand of the Red Letter "dangerous. But what is the danger? Will the tree fall? Waste mine? Bigfoot? Unless notified

What is the danger or the danger is very obvious, otherwise this brand will not help people to be alert, people will

Ignore the warning on the brand. Similarly, assertions that programmers do not understand will also be ignored. In this case, the programmer will think

The corresponding assertions are incorrect and are removed from the program. Therefore, to enable programmers to understand the intent of assertions,

Annotations should be added to unclear assertions.

 

@ Is not used to check for errors

When programmers start to use assertions, they sometimes mistakenly Use assertions to check for real errors rather

. Take a look at the following function strdup
Two assertions in:

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 non-

Method. The usage of the second assertion is quite different. What it tests is an error and it will definitely result in the final product.

And must be processed.

 

(Note: "errors" here refer to "exceptions" in the C language interface and implementation ".)

 

@ Do not conceal errors when designing error-proof programs

Before coding, you should ask yourself: "Is there any concealment error in the program during error-proof programming ?" If the answer is yes, you need to add the corresponding assertions in the program to alert these errors.

@ Avoid overuse

Assertions may also be over-used. Users must be flexible in understanding how to use assertions. For example, for some programmers, each division uses assertions to check whether the denominator is 0.
It may be important, but it may be ridiculous for other programmers. The user must weigh the balance.

 

@ Do not confuse the differences between illegal and wrong situations

Use assertions to capture exceptions that should not occur. Do not confuse the differences between illegal situations and error situations. The former indicates that the code is illegal (that is, the contract referred to in the C interface), and the latter must be handled in the final product.

Neil inning. Linux. Programming 3rd Neil Matthew, Richard
Stones

 

Chapter 10: Debugging

Assertions

While it's common to introduce debug Code such as printf cals, possibly by Conditional compilation,

During the development of a program, it's sometimes impractical to leave these messages in a delivered

System. However, it's often the case that problems occur during the program operation that are related

To incorrect assumptions rather than coding errors. These are events that "can't happen." For example,

Function may be written with the understanding that its input parameters will be within a certain range.

If it's passed incorrect data, it might invalidate the whole system.

For these cases, where the internal logic of the system needs to be confirmed, X/Open provides

Assert macro that can be used to test that an assumption is correct and halt the program if not.

# Include <assert. h>

Void assert (INT expression)

The assert macro evaluates the expression and, if it's nonzero, writes some diagnostic information

The standard error and callabort to end the program

 

The header file assert. h defines the macro depending on the definition of ndebug. If ndebug is

Defined when the header file is processed, assert is defined to be essentially nothing. This means that

You can turn off assertions at compile time by compiling with-dndebug or by including the line

# Define ndebug

In each source file before including assert. h.

This method of use is one problem with assert. If you use assert during testing, but turn it off

Production Code, your production code cocould have less safety checking than when you are testing it.

Leaving assertions enabled in production code is not normally an option-wocould you like your code

Present a customer with the unfriendly error assert failed and a stopped program? You may consider

It better to write your own error trapping routine that still checks the assertion but doesn't need to be

Completely disabled in production code.

You must also be careful that there are no side effects in the assert expression. For example, if you use

Function call with a side effect, the effect won't happen in the production code if assertions are removed.

 

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.