ASSERT (programming terminology)

Source: Internet
Author: User

assert (programming terminology)
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.
Chinese name
Assert
Pre-condition assertion
features that you must have before code execution
Explain
Maintain, uphold, hold, assert, etc
Note
assert is a macro, not a function
Directory
    1. 1 Assertion Features
    2. 2 How to use
    3. 3 Java assertions
    4. 4 using Assertions
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 attribute Edit Precondition Assertion: attribute post-conditional assertion that code must have before it executes: attributes that must be followed before and after code execution assertions: features that cannot be changed before or after code execution the assertion can have two forms of 1.assert Expression12.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 asserts that edit assertions are turned off by default, to enable assertions at compile time, to use the source1.4 tag, which is Javac source1.4 Test.java, to enable assertions at run time using-ea parameters. To enable and disable assertions in a system class, you can use the-ea and-DSA parameters. For example:
123456789 publicclassAssertExampleOne{    publicAssertExampleOne(){}    publicstaticvoidmain(String args[]){        int x=10;        System.out.println("Testing Assertion that x==100");        assertx==100:"Out assertion failed!";        System.out.println("Test passed!");    }}
If the compile time is not-source1.4, then the compile pass does not add-ea when the output is testing assertion that x==100test Passed!jre ignored the assertion of the old code, and the use of this parameter will be output as testing assertion that x==100exception in thread "main" Java.lang.AssertionError:Out assertion Failed!at Assertexampleone.main ( Assertexampleone.java:6) assertion of side effects due to programmer's problem, the use of assertions may bring side effects, such as: Boolean isenable=false;//...
Assert isenable=true; the side effect of this assertion is that it modifies the value of a 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.
12345678910 publicclass AssertExampleTwo{    publicstaticvoidmain(String args[]){        booleanisEnable=false;        //...        assertisEnable=true;        if(isEnable==false){            thrownewRuntimeException("Assertion should be enable!");        }    }}
Using assertions to edit 1. You can place assertions in places where the program is not expected to arrive normally: Assert false2. Assertions can be used to check parameters passed to private methods. (For public methods, because it is provided to the external interface, it is necessary to have a corresponding parameter test in the method to ensure the robustness of the Code) 3. Use the Assert test method to perform the preconditions and the post condition 4. Use assertions to check the invariant state of a class, ensuring that the state of a variable must be satisfied in any case. (such as the age attribute should be greater than 0 less than an appropriate value) without asserting that the assertion statement is not always executed, Can be masked or enabled therefore: 1. Do not use assertions as parameter checks for public methods, and the parameters of public methods are always executed 2. Assertion statements cannot have any boundary effects, do not use assertion statements to modify variables and change the return value of a method. C macro macro Name: AssertFunction: Tests a condition and may cause the program to terminate usage: void assert (int test), program example:
12345678910111213141516171819 #include<assert.h>#include<stdio.h>#include<stdlib.h>structITEM{    intkey;    intvalue;};/*add item to list,make sure list is not null*/voidadditem(structITEM* itemptr){    assert(itemptr!=NULL);    /*additemtolist*/}intmain(void){    additem(NULL);    return0;}
assert () macro usageNote: 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:
123456 #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. [1] Take a look at the following list of programs BADPTR.C:
12345678910111213 #include<stdio.h>#include<assert.h>#include<stdlib.h>intmain(void){    FILE* fp;    fp=fopen("test.txt","w");//以可写的方式打开一个文件,如果不存在就创建一个同名文件    assert(fp);//所以这里不会出错    fclose(fp);    fp=fopen("noexitfile.txt","r");//以只读的方式打开一个文件,如果不存在就打开文件失败    assert(fp);//所以这里出错    fclose(fp);//程序永远都执行不到这里来    return0;}
[[email protected] error_process]# gcc badptr.c[[email protected] error_process]#./a.outa.out:badptr.c : 14:main:assertion ' FP ' failed. If you use dynamic link libc, __line__, except __file__, __assert_function, will make the target a little bit larger, not because the ASSERT is used multiple times ( ) to increase the number of goals. 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 # <assert.h>, the sample code is as follows: #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,//Parameters: 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 a problem 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 < i++;4) Assert and subsequent statements should be blank line to form logical and visual 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:"); Break;default:debug.assert (false); break;}

ASSERT (programming terminology)

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.