Java assert usage and in-depth parsing of Java assertion

Source: Internet
Author: User

Java assert usage and in-depth parsing of Java assertionCategory: Java2012-12-05 13:32 2020 people read Comments (0) favorite reports

Source: http://blog.csdn.net/wguoyong/article/details/6909828. Thank you, author.

Assert expression1;
Assert Expression1:expression2;
If expression1 is true, no error is thrown, the program runs correctly, and expression2 is not executed.
If Expression1 is false, an exception is thrown, the program breaks out, and expression2 executes.

In general, do not use the return value of the function in expression1, expression2;
Do not use it to check input parameters in the public function, but you can use it to detect input parameters in the private function.

When you use it, you need to use javac-source at compile time; Java-ea is required for execution.


Personal understanding: Using Assert is just to help us debug the program, so the principle of using Assert is "no change in the structure of the program because of the presence of an Assert", which is plainly "if you delete the Assert part, There is still no problem with the program, but it does not help us to check for errors, so we should not use the function in the expression when using assert, because once this assert statement is deleted, the structure of the program changes, which does not conform to the above mentioned principle!

Attach a very good written text:

Deep analysis of Java assertion

First, the grammar and semantics of assertion

J2SE 1.4 provides a new feature in the language, which is the assertion (assertion) feature, which is the biggest innovation in the Java language for this version. In software development, assertion is a kind of classic debugging, testing method, this article will deeply analyze the use of assertion function and its design concept, and give relevant examples.

Assertion (assertion) is a common debugging method in software development, and many development languages support such mechanisms, such as c,c++ and Eiffel, but the forms of support are not the same, either through the language itself or through library functions. In addition, theoretically, through the assertion way can prove the correctness of the program, but this is a rather complex work, there is not much practical significance.

In the implementation, assertion is a statement in the program, which checks a Boolean expression, a correct program must ensure that the value of the Boolean expression is true, if the value is False, the program is already in an incorrect state, The system will give a warning or exit. In general, assertion is used to ensure the most basic and critical correctness of the program. Assertion inspection is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released. The following is a brief introduction to the implementation of assertion in Java.

1. 1) syntax representation

In syntax, a keyword assert was added to support Assertion,java. It consists of two expressions, as follows:

    1. Assert expression1;
    2. Assert Expression1:expression2;

In both expressions, expression1 represents a Boolean expression, Expression2 represents a base type or an object, and the base types include boolean,char,double,float,int and long. Because all classes are subclasses of object, this parameter can be used for all objects.

1. 2) semantic meaning

At run time, these statements will have no effect if the assertion feature is turned off. If the assertion function is turned on, then the value of expression1 is evaluated and if its value is false, the statement strongly throws a Assertionerror object. If the assertion statement includes the expression2 parameter, the program calculates the result of the expression2, and then takes the result as an argument to the Assertionerror constructor, creating the Assertionerror object and throwing the object If the expression1 value is true,expression2, it will not be evaluated.

In a special case, if the expression itself throws exception when the expression is evaluated, assert stops running and throws the exception.

1. 3) Some assertion examples

Here are some examples of assert.

    1. Assert 0 < value;
    2. Assert 0 < value: "Value=" +value;
    3. ASSERT ref! = null: "ref doesn ' t equal null";
    4. Assert isbalanced ();

1. 4) Compiling

Because assert is a new keyword, using an older version of the JDK is not possible to compile a source program with an assert. Therefore, we must use the JDK1.4 (or newer) Java compiler, when using the Javac command, we must add-source 1.4 as the parameter. -source 1.4 means that the source code is compiled using JDK version 1.4, otherwise the compilation will not pass because the default Javac compiler uses JDK1.3 syntax rules.

A simple example is as follows:

Javac      -source   1.4    Test.java

1. 5) Run

Because a program with an Assert statement is running, the new ClassLoader and class classes are used, so the program must run under the JDK1.4 (or later) JRE, and not in the older version of the JRE.

Since we can choose to turn on the assertion function or not, we can also turn on some of the assertion features of the class or package, so the run option becomes somewhat complex. With these options, we can filter all classes that we don't care about, just select the classes or packages we care about to see. Two types of parameters are described below:

  1. Parameters -esa and -DSA:
    They mean to turn on (off) the assertion function of the system class. Because of the new version of the Java System class, also makes the assertion statement, so if users need to observe their operation, you need to open the System class assertion function, we can use the-esa parameter open, using the-DSA parameter to close.
    The full name of-esa and-DSA is-enablesystemassertions and-disenablesystemassertions, and the full name and abbreviated name have the same function.
  2. Parameters-eaAnd-ea
    They mean to turn on (off) the assertion function of the user class: With this parameter, the user can open certain classes or packages of the assertion function, and the same user can turn off some classes and package assertion functionality. Open the Assertion function parameter is-ea, if you open all user classes without any parameters, if you have a package name or class name, you open these classes or packages, if the package name is followed by three points, it represents the package and its child packages, and if there are only three points, it represents the nameless package. Turning off the assertion function parameter is-da, which is similar to-ea.
    The full name of-ea and-da is-enableassertions and-disenableassertions, and the full name and abbreviated name have the same function.
    The following table shows the parameters and their meanings, with examples of how to use them.
     
    Parameters Example Description
    -ea Java-ea Open assertion for all user classes
    -da Java-da Turn off assertion for all user classes
    -ea:<classname> Java-ea:myclass1 Open MyClass1 's assertion.
    -da:<classname> Java-da:myclass1 Close MyClass1 's assertion
    -ea:<packagename> Java-ea:pkg1 Open the assertion of the PKG1 package
    -da:<packagename> Java-da:pkg1 Close the assertion of the PKG1 package
    -ea: ... Java-ea: ... Open the assertion of the default package (Nameless package)
    -da: ... Java-da: ... Turn off the assertion of the default package (unnamed package)
    -ea:<packagename>, ..... Java-ea:pkg1 ... Open the assertion of the PKG1 package and its child packages
    -da:<packagename>, ..... Java-da:pkg1 ... Close the assertion of the PKG1 package and its child packages
    -esa Java-esa Open the assertion of the system class
    -dsa Java-dsa Turn off the assertion of the system class
    Integrated use Java-dsa:myclass1:pkg1 Close the assertion of the MYCLASS1 and PKG1 packages

    where ... Represents the meaning of this package and its child package. For example we have two packages for Pkg1 and pkg1.subpkg. So pkg1 ... On behalf of PKG1 and pkg1.subpkg two packages.
    In addition, Java, in order to allow the program to dynamically turn on and off some classes and packages of the assertion function, Java fixed the class and classloader implementation, adding a few to operate the Assert API. Here's a brief explanation of how several APIs work.
    Several related APIs in the ClassLoader class:
    Setdefaultassertionstatus: Used to turn the assertion function on/off
    Setpackageassertionstatus: Assertion function to turn some packages on/off
    Setclassassertionstatus: Assertion function to turn on/off some classes
    Clearassertionstatus: Used to turn off the assertion function
     

Second, the design problem of assertion

First of all, we think that assertion is necessary. Because, without a unified assertion mechanism, Java programs typically use If-then-else or switch-case statements for assertion checks, and the data types that are checked are not identical. The assertion mechanism allows Java programmers to handle assertion problems in a unified manner, rather than handling them in their own way. Also, if the user checks in their own way, the code will still work after publishing, which can affect the performance of the program. The assertion function is supported from the language level, which minimizes the negative impact of assertion on performance.

Java is supported assertion by enhancing a keyword assert implementation, rather than using a library function support, which suggests that Java considers assertion to be very important for the language itself. In fact, Java was able to support assert in the early specification of Java, but because of some implementation limitations, these features were removed from the specification. Therefore, the re-introduction of assert should be the restoration of Java support for assert. The C language is supported by the ASSERT.H function library to implement assertions.

Java assertion is not the same as the C language, we all know that in the C language, assertion's opening is at compile time to decide. When we compile the program using debug mode, the assertion is turned on, and the assertion is automatically turned off when compiling using the release method. Java's assertion is determined at run time. In fact, both of these approaches have advantages and disadvantages. With a compile-time decision, the developer will handle two types of target code, debug version and release version, which increases the difficulty of document management, but improves the efficiency of the Code. Java takes a run-time decision so that all assertion information is placed in the target code, the same target code can be run in different ways, enhancing the flexibility of the target code, but it will sacrifice some of the performance penalty because of assertion. The Java panel believes that the performance sacrifices are fairly small, so Java uses the runtime decision method.

In addition, we notice that Assertionerror is a subclass of error, not runtimeexception. In this regard, the Panel also had a long discussion. The error represents some unusual errors, which are usually not recoverable, and runtimeexception emphasizes the characteristics of the error that occurs at run time. Assertionerror are often very critical errors, which are often not easily recoverable, and the assertion mechanism does not encourage programmers to recover from such errors. Therefore, in order to emphasize the meaning of assertion, the Java Expert Group chose to make Asserterror a subclass of error.

Third, assertion and inheritance

In this section, we will consider the relationship between assertion and inheritance and study how assert is positioned. If the assertion of a subclass is turned on, does the assertion of its parent class execute?

The following example shows if an Assert statement is in the parent class, and when its subclasses call it, the Assert is false. Let's see if the assertion is handled under different circumstances.

Class Base{public void Basemethod () {Assert      false: "Assertion Failed:this is Base";// Always assertion failure System.out.println ("Base Method");}} Class derivedextends base{public void Derivedmethod () {Assert false: "Assertion Failed:this is derive";// Always assertion failure System.out.println ("Derived Method");} public static void Main (string[] args) {try{derived Derived = new Derived ();d Erived.basemethod (  ); Derived.derivedmethod ();} catch (Assertionerror ae) {System.out.println (AE);}}}

Run command Meaning Results
Java Derived Do not enable assertion Base Method
Derived Method
Java-ea Derived Open All assertion Java.lang.AssertionError:Assertion Failed:this is base
Java-da Derived Close all assertion Base Method
Derived Method
Java-ea:base Derived Open only the base assertion Java.lang.AssertionError:Assertion Failed:this is base
Java-ea:derived Derived Open only the derived assertion Base Method
Java.lang.AssertionError:Assertion Failed:this is derived

As we can see from this example, the Assert statement of the parent class will only work if the parent class's assert is turned on, and if only the assert of the subclass is turned on, the assert of the parent class is still not running. For example, when we execute java-ea:derived Derived, the base class Assert statement is not executed. Therefore, we can assume that the Assert statement does not have an inheritance function.

Iv. use of assertion

The use of assertion is a complex issue, as it will involve the style of the program, the assertion application of the object, the nature of the program, and so on. In general, assertion is used to check for some key values, and these values have a significant impact on the completion of the entire program, or the local functionality, and this error is not easily recoverable. Assertion expressions should be short and understandable, and function calculations should be used if complex expressions need to be evaluated. Here are some examples of scenarios that use assertion, which can make Java programs more reliable.

  1. Check the control flow; in the If-then-else and swith-case statements, we can add the assert false statement to the control tributary that should not occur. If this happens, the assert can be checked out.
    For example: X can only be used to make only a few, our program can be represented as follows
     
    Switch (x)    {Case 1: ...;    Case 2: ...;    Case 3:    ... Default:assert false: "x value is invalid:" +X;    }    
  2. Check that the input parameters are valid before the private function is evaluated; for some private functions that require input to satisfy certain conditions, we can use assert at the beginning of the function to check the parameters. For public functions, we typically do not use the assertion check because, in general, public functions must check and handle invalid parameters. Private functions are often used directly.
    For example, a function may require that the input parameter must not be null. Then we can add an assert parameter1!=null at the beginning of the function: "Paramerter is a null in test method";
  3. After the function is evaluated, check that the function result is valid; For some calculation functions, some values need to be guaranteed to be of a certain nature after the function is run, so we can check the value by Assert.
    For example, we have a function that calculates the absolute value, so we can add a statement at the result of the function:
     
    Assert  value>=0: "Value should be bigger than 0:" +value;
    In this way, we can check the results of the function calculation.
  4. Check program invariants; In some programs, there are invariants, and the values of these invariants are constant during the program's running life cycle. These invariants may be a simple expression or a complex expression. For some key invariants, we can check with assert.
    For example, in an accounting system, the company's expenditure and income must maintain a certain balance, so we can write an expression to check the balance, as shown below.
     
              Private Boolean isbalance () {    ...    }    
    In this system, we can add assert verification before and after some methods that may affect this equilibrium: Assert Isbalance (): "Balance is destoried";
     

V. Conclusion

Assertion provides developers with a flexible debugging and testing mechanism that is simple and easy to use. However, how to standardize and systematically use assertion (especially in the Java language) is still a problem that needs to be researched.

Java assert usage and in-depth parsing of Java assertion

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.