Assert
When writing code, we always make assumptions that assertions are used to capture these assumptions in code, and assertions can be thought of as an advanced form of exception handling. Assertions are expressed as Boolean expressions, and programmers believe that the expression value is true at a particular point in the program. Assertion validation can be enabled and disabled at any time, so you can enable assertions while you are testing, and disable assertions at deployment time. Again, when the program is running, the end user can re-assert the assertion when it encounters a problem.
Basic explanation
and Object Verb vt.
1. Assert, claim [+THAT][O2]
She asserted her innocence.
She claimed that she was innocent.
He asserted that he is not guilty.
He declared his innocence.
2. Maintain, persist, assert
The boss asserted his authority by punishing he employees.
The boss defended his authority by punishing his employees.
3. Show, establish, declare, maintain, claim
Usage in C
Use assertions to create more stable, better-quality, and less error-prone code. You can use assertions when you need to break the current operation with a value of false. Unit tests must use assertions (JUNIT/JUNITX).
In addition to type checking and unit testing, assertions provide an excellent way to determine whether a variety of features are maintained in a program.
The use of assertions allows us to move closer to a contract-based design.
Assertion attributes
Preconditions assertion: Features that must be in place before code executes
Post-Conditional assertion: Features that must be available after code execution
Invariant assertion: Features that cannot be changed before and after code execution
How to use
Assertion is valid only in debug mode, it can have two forms
1.assert Expression1
2.assert Expression1:expression2
Where Expression1 should always be a Boolean value, Expression2 is the string of failed messages that are output when the assertion fails. If Expression1 is false, it throws a assertionerror, which is an error, not an exception, that is, an uncontrollable exception (unchecked Exception), assertionerror because it is an error, So you can not capture, but it is not recommended, because that will put your system into an unstable state.
Java Assertion
Assertions are turned off by default, to enable assertions at compile time, you need to use the source1.4 tag both Javac source1.4 Test.java, and the-ea parameter is required to enable assertions at run time. To enable and disable assertions in a system class, you can use the-ea and-DSA parameters.
For example:
publicclassassertexampleone{
Publicassertexampleone () {}
Publicstaticvoidmain (stringargs[]) {
intx=10;
System.out.println ("testingassertionthatx==100");
assertx==100: "outassertionfailed!";
System.out.println ("testpassed!");
}
}
If-source1.4 is not added at compile time, the compile pass
Output as-ea when execution is not added
Testing assertion that x==100
Test passed
The JRE ignores the old code for the assertion, and the parameter is used to output the
Testing assertion that x==100
Exception in thread "main" Java.lang.AssertionError:Out assertion failed!
At Assertexampleone.main (assertexampleone.java:6)
Side effects of assertions
Because of a programmer's problem, the use of assertions can cause side effects, such as:
Boolean isenable=false;
//...
Assert isenable=true;
The side effect of this assertion is that it modifies the value of the variable in the program and does not throw an error, which is difficult to find if not carefully examined. But at the same time we can get a useful feature based on the side effects above and test the assertion to see if it is open.
publicclassassertexampletwo{
Publicstaticvoidmain (stringargs[]) {
Booleanisenable=false;
//...
Assertisenable=true;
if (Isenable==false) {
Thrownewruntimeexception ("assertionshoulebeenable!");
}
}
}
Using assertions
1. The assertion can be placed where the program is expected to not arrive in normal circumstances: assert false
2. Assertions can be used to examine parameters passed to a private method. (For public methods, because it is provided to the external interface, you must have a corresponding parameter test in the method to ensure the robustness of the code)
3. Preconditions and post conditions that are performed using the Assert test method
4. Use assertions to check the invariant state of a class to ensure that the state of a variable must be met in any case. (If the age attribute should be greater than 0 less than a suitable value)
No assertions.
Assertion statements are not always executed, can be masked, or can be enabled
So:
1. Do not use assertions as parameter checks for public methods, the parameters of public methods are always executed
2. Assert statements can have no boundary effect, do not use assertion statements to modify variables and change the return value of a method.
The macro in C
Macro Name: Assert
Function: Test a condition and possibly terminate the program
Usage: void assert (int test);
program Example:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
Structitem
{
Intkey;
Intvalue;
};
/*additemtolist,makesurelistisnotnull*/
Voidadditem (STRUCTITEM*ITEMPTR)
{
ASSERT (Itemptr!=null);
/*additemtolist*/
}
Intmain (void)
{
AddItem (NULL);
Return0;
}
ASSERT () macro usage
Note: Assert is a macro, not a function. In the assert.h header file of C.
The prototype of an Assert macro is defined in <assert.h>, and its function is to terminate the execution of the program if its condition returns an error, and the prototype defines:
#defineassert (expr) \
(expr) \
? __assert_void_cast (0) \
: __assert_fail (__string (expr), __file__,__line__,__assert_function))
/*definedinglibc2.15*/
The role of assert is to evaluate the expression expr first, if its value is false (that is, 0), then it will print out the ASSERT content and __file__, __line__, __assert_function, and then execute abort () The function causes kernel to kill itself and coredump (whether to generate Coredump files, depending on the system configuration); otherwise, assert () has no effect. Macro assert () is generally used to confirm the normal operation of the program, where the expression construction is not a mistake for truth. After debugging is complete, you do not have to remove the ASSERT () statement from the source code because the macro ndebug definition is empty.
Take a look at the following program listing BADPTR.C:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
Intmain (void) {
FILE*FP;
Fp=fopen ("Test.txt", "w");//Open a file in a writable manner and create a file with the same name if it does not exist
ASSERT (FP);//So there's nothing wrong here.
Fclose (FP);
Fp=fopen ("Noexitfile.txt", "R");//Open a file in a read-only manner and open the file if it does not exist
ASSERT (FP);//So error here
Fclose (FP);//programs are never executed here.
Return0;
}
[Email protected] error_process]# gcc badptr.c
[Email protected] error_process]#./a.out
A.out:badptr.c:14:main:assertion ' FP ' failed.
If you use dynamic link libc, in addition to __file__, __line__, __assert_function will make the target a little bit larger, and will not increase the target many times by using ASSERT (). But the benefits are obvious, that is, the name of the file, the number of rows, and the function name will be printed in the Assert place. Also, be aware of the degree of error with assert (). If the condition of the Assert () is fail, then the abort () function is called to let kernel kill itself, even if the user re-registers the behavior of the SIGABRT signal (abort () will send itself a signal SIGABRT to ensure that the user's handler properly executed, Then modify the behavior of the SIGABRT signal as the default behavior Coredump, again sending sigabrt,coredump like yourself).
After debugging, you can disable the Assert call by inserting the #define NDEBUG before the statement that contains # include <assert.h>, as shown in the following example code:
#include <stdio.h> #define Ndebug#include <assert.h>
Usage Summary and Precautions:
1) Verify the legitimacy of incoming parameters at the beginning of the function
Such as:
int resetbuffersize (int nnewsize) {//function: Change buffer size,//parameter: Nnewsize buffer new Length//return value: Buffer current Length//Description: Keep the original information content unchanged nnewsize<= 0 means clear buffer assert (nnewsize >= 0); ASSERT (Nnewsize <= max_buffer_size); ...}
2) Each assert examines only one condition, because when multiple conditions are checked, if the assertion fails, it is not possible to visually determine which condition failed
/*** Bad ***/assert (noffset>=0 && noffset+nsize<=m_ninfomationsize)/**** good ****/assert (nOffset >= 0); ASSERT (Noffset+nsize <= m_ninfomationsize);
3) You cannot use a statement that alters the environment, because assert only works in debug, and if you do, you will use the program to run into problems when it is actually running
Error: Assert (i++ < 100)
This is because if there is an error, such as i=100 before execution, then this statement will not be executed, then i++ This command will not be executed.
Correct: Assert (I < 100)
i++;
4) Assert and subsequent statements should be empty lines to create a logical and visual sense of consistency
5) In some places, assert cannot replace conditional filtering
Note: When for floating-point numbers:
#include <assert.h>float pi=3.14f;assert (pi==3.14f);
Always have a default clause in the switch statement to display information (Assert).
int number = SomeMethod (), switch (number) {Case 1:trace.writeline ("Case 1:"), break, Case 2:trace.writeline ("Case 2:"); b Reak; Default:Debug.Assert (FALSE); break;}
Assert assertion Test