In-depth analysis of Java's new feature Assertion

xiaoxiao2021-03-06  105

In-depth analysis of Java's new feature Assertion

content:

Assertion's grammar and semantic assertion design problem assertion and inheritance assertion conclusion Reference information about the author

There is also a Java area:

Teaching tools and product code and components all articles practical skills

Ouyang Chen (Yeekee@sina.com) Zhouxin@sei.pku.edu.cn) June 2002 Assrtion's grammatical and semantic J2SE 1.4 provided a new feature on language, is the Assertion function, It is the largest innovation in Java language. In software development, Assertion is a classic debugging, test mode, which will in depth, in depth, the use of Assertion features and its design concept, and give relevant examples. Assertion is a commonly used commissioning in software development. Many development languages ​​support this mechanism, such as C, C and Eiffel, etc., but supported forms are not the same, and some through the language itself, some through the library Function, etc. In addition, in theory, through the ASSERTION method can prove the correctness of the program, this is a quite complex work, there is no much practical significance. In the implementation, Assertion is a statement in the program that checks a Boolean expression. A correct program must ensure that this Boolean expression is true; if the value is false, the program is already in an incorrect state. Next, the system will give a warning or exit. In general, Assertion is used to ensure the most basic and key correctness of the program. Assertion checks are usually opened when developed and tested. In order to improve performance, the assertion check is usually closed after the software is released. The following is a brief introduction to the implementation of Ascertion in Java. 1.1) The syntax is indicated in the grammatical, in order to support Assertion, Java adds a keyword Assert. It includes two expressions, as follows:

Assert Expression1; Assert Expression1: Expression2; In both expressions, Expression1 represents a Boolean expression, Expression2 represents a basic type or an object (Object), the basic type includes Boolean, CHAR, DOUBLE, FLOAT, INT, and LONG. This parameter can be used for all objects because all classes are subclasses of Object. 1.2) Semantic meaning is running, if the assertion function is turned off, these statements will not work. If you open the assertion feature, the value of Expression1 will be calculated if it is false, the statement strongly throws an AssertionError object. If the assertion statement includes an Expression2 parameter, the program will calculate the result of Expression2, and then use this result as a parameter of the constructor of the assertionerror, and throw the object; if the Expression1 value is true, Expression2 will not be calculated. A special case is that if the expression itself throws Exception if the expression is calculated, the Assert will stop running and throw this Exception. 1.3) Some Assertion Examples are some assert examples.

Assert 0

Parameter Example Illustrates - EAJAVA-EA Open All User Class ASSERTION-DAJAVA -DA Close All User Class ASSERTION-EA: java -ea: myclass1 Open myclass1 Assertion-Da: java -da: myclass1 close Myclass1 Assertion-Ea: Java-EA: PKG1 opens the Assertion-Da: java -da: PKG1 close the PKG1 package for the PKG1 package........ Assertion-da: ... java -da: ... Java-Da: ... close off the default package (unknown package) ASSERTION-EA: ... Java -ea: Pkg1 ... Open PKG1 Assertion-da: ... java -da: pkg1 ... close off the PKG1 package and its sub-package Assertion-DSAJAVA-DSA Turn system class Assertion uses Java-DSA: MyClass1: PKG1 to close the ASSERTION of MyClass1 and Pkg1 packs ... representative, the meaning of this package and its subcare. For example, we have two packages for pkg1 and pkg1.subpkg. Then pkg1 ... represents two packages of PKG1 and Pkg1.Subpkg. In addition, Java has enabled the program to dynamically turn the assertion feature of certain classes and packages, Java has tried the implementation of Class and ClassLoad, and adds several APIs for operating Assert. The following is a brief explanation of several API functions. Several related APIs in the ClassLoader class: SETDEFAULTASERTIONSTATUS: Used to turn on / off AssertionStatus: ASSERTIONTATUS for opening / closing some packages SETCLASSSSERTIONSTATUS: Used to turn on / close some classes of Assertion function ClearassertionsTatus: Used to close Assertion function 2 Assertion design problem First, we think Assertion is necessary. Because, if there is no unified assertion mechanism, Java programs typically use the if-dam-else or switch-case statement for Assertion check, and the data type checking is not exactly the same. The Assertion mechanism allows the Java programmers to handle the assertion problem in a unified manner instead of processing it in its own way. Also, if the user checks in its own way, these code will still work after publishing, which may affect the performance of the program. The Assertion function is supported from the language level, which will minimize the negative impact of Assertion to performance. Java is to support Assertion by enhancing a keyword assert, rather than using a library function support, this shows that Java believes that Assertion is very important for the language itself. In fact, in the early specifications of Java, Java can support Assert, but these features are removed from the specification due to some implementation restrictions. Therefore, the reheadation of Assert should be to restore Java's support for Assert. The C language is the support of the assertion through the assert.h function library. Java's ASSERTION is also not the same as the C language, we all know that in the C language, the ASSERTION is determined when compiling.

When we use the Debug mode to compile the program, the assertion is turned on, and the assertion is automatically closed when using the Release mode. Java's assertion is determined when running. In fact, these two ways have their own advantages and disadvantages. If you use compile time decisions, developers will handle two types of target code, debug version, and release, which increases the difficulty of document management, but improves code running efficiency. Java uses the runtime decision, so all Assertion information will be placed in the target code, and the same target code can be used to run, enhance the flexibility of the target code, but it will sacrifice because of Assertion causes a part of the performance loss. The Java expert team believes that the performance of the sacrifices is quite small, so Java uses runtime decisions. Also, we noticed AssertionError as a subclass of Error, not RuntimeException. In this regard, the expert group also conducted a long-term discussion. Error represents some abnormal errors, usually not recovered, and RuntimeException emphasizes the feature that the error occurs at runtime. AssertionError is usually a very critical error that is often not easy to recover, and the ASSERTION mechanism does not encourage programmers to recover such errors. Therefore, in order to emphasize the meaning of Assertion, the Java expert group chose a subclass of the asserterror as Error. Three Assertions and Inheritance In this section, we will consider the relationship between Ascertion and inheritance, how is the Assert is positioned. If you turn on an Assertion of a subclass, is its parent class assertion executed? The following example will display if an ASSERT statement is in the parent class, and when its subclass calls it, the assert is false. We look at whether the assertion is processed in different situations. Class base {

Public void basemethod ()

{

Assert False: "Assertion Failed: this is base"; // always Assertion failed

System.out.println ("Base Method");

}

}

Class Derived

Extends Base

{

Public void derivedmethod ()

{

askERT FALSE: "Assertion Failed: this is deive"; // Always assing failed

System.out.println ("Derived Method");

}

Public static void main (string [] args)

{

Try

{

Derived derived = new derived ();

Derived.basemethod ();

Derived.derivedMethod ();

}

Catch (Assertionerror AE)

{

System.out.println (AE);

}

}

}

Run the command does not enable the meaning of the results Java Derived assertionBase MethodDerived MethodJava -ea Derived Open All assertionJava.lang.AssertionError: Assertion Failed: This is baseJava -da Derived close all assertionBase MethodDerived MethodJava -ea: Base Derived open only assertionJava.lang.AssertionError Base of : Assertion failed: this is basejava -ea: derived derived Only open Derived assertionBase Methodjava.lang.assertionerror: assertion failed: this is deive from this example we can see that the parent class's Assert statement will only be turned on in the parent class Just play, if only the ASSERT of the subclass is turned, the parent class's Assert is still not running. For example, when we execute java -ea: derived derived, the Assert statement of the Base class does not execute. Therefore, we can think that the Assert statement does not have inheritance. The use of four Assertions is a complex problem because this will involve the style of the program, the goal of Assertion, the nature of the program. In general, Assertion is used to check some key values, and these values ​​have a big impact on the entire program, or the completion of local functions, and this error is not easy to recover. The Assertion expression should be short, easy to understand, if a complex expression is required, the function is calculated. Here are some examples of situations using assert, which allows Java programs to be higher. Check the control flow; in the if-kilse and switch-case statements, we can add the Assert False statement on the control tribunition that should not occur. If this happens, Assert can check it out. For example: X value can only make 1, 2, 3, and our programs can be represented by Switch (X)

{casse 1: ...;

Case 2: ...;

Case 3: ...

DEFAULT: Assert False: "x value is invalid:" x;

}

Check whether the input parameter is valid before the private function is calculated; for some other functions, you can enter some specific conditions, then we can use Assert to use Assert to check the parameter check at the beginning of the function. For public functions, we usually do not use Assertion check, because in general, public functions must check and process invalid parameters. And private functions are often used directly. For example, a function may require input parameters to be NULL. Then we can add Assert Parameter1! = Null: "Paramerter Is Null in Test Method"; After the function is calculated; for some computing functions, some values ​​need To ensure a certain nature, we can check this value via Assert. For example, we have a function of calculating the wrong value, then we can at the results of the function, plus a statement: assert value> = 0: "Value Should Be Bigger Than 0:" value; In this way, we The result of the function calculates can be checked. Check the program invariant; some procedures, there are some invariant, in the run life cycle of the program, these invariant values ​​are constant. These invariance may be a simple expression or a complex expression. For some key non-variables, we can check them via Assert. For example, in a financial system, the company's spending and income must maintain a certain balance relationship, so we can write an expression to check this balance relationship, as follows. Private boolean isbalance () {...

}

In this system, we can add Assert. "Assert isbalance ():" Balance is destoried "; five conclusions provide developers with a flexible debugging And test mechanisms, it is also very simple and convenient. However, how to specify, systematically use Assertion (especially in the Java language) is still an urgent problem. Reference:

JSR 41 A Simple Assertion facilityHttp: //jcp.org/jsr/detail/41.jsp WM. Paul Rogers, J2SE 1.4 Premieres Java's assertion Capabilitieshttp://www.javaworld.com/javaworld/jw 18-2001/jw- 1109-Assert.html? J2se 1.4 documents, programing with assertshtp: //java.sun.com/j2se/1.4/docs/guide/lang/assert.html John Zukowski, Mastering Java 2, J2SE 1.4

About the author of Ouyang Chen, Beijing University Computer Department graduated, starting to study Java-based software development, test, participation, and test multiple Java-based applications and Web service items in 1998. Contact Yeekee@sina.com Zhou Xin, Peking University Computer Department is reading doctoral student, main research direction: program understanding, reverse engineering and software metrics, contact information zhouxin@sei.pku.edu.cn.

转载请注明原文地址:https://www.9cbs.com/read-104602.html

New Post(0)