Use of assertions in Java

Source: Internet
Author: User
I believe that those who have learned C and C ++ will not be unfamiliar with assertions. The following describes how to use assertions in Java. JAVA supports assertions starting from jdk1.4 (the keyword assert is added). Note that the old version of JRE does not support them.


Assertion Overview

When writing code, we always make assumptions. assertions are used to capture these assumptions in the code.
Assertion can be viewed as an advanced form of exception handling.
Assertions are expressed as boolean expressions. The programmer believes that the expression value is true at a specific point in the program.
You can enable and disable Assertion Verification at any time, so you can enable assertion during testing and disable assertion during deployment. Similarly, after the program is put into operation, the end user can re-use the assertions in case of problems.
Using assertions, you can create code with higher stability, better quality, and easier debugging.
You can use assertions to interrupt the current operation when the value is false.
Unit tests must use assertions (JUnit/junitx)
In addition to type checks and unit tests, assertions also provide an excellent way to determine whether a feature is maintained in the program.
Using assertions brings us closer to a contractual design


Common assertions

Preconditions assertions: features required before Code Execution
Post-condition assertions: features required after Code Execution
Unchanged assertion: Non-changeable features before and after Code Execution


Assertion usage

Assertion can be in two forms
1. Assert expression1
2. Assert expression1: expression2
Expression1 should always be a Boolean value, and expression2 is the string of the failed message output when the assertion fails. If expression1 is false, an assertionerror is thrown. This is an error rather than an exception, that is, an unchecked exception. assertionerror is not captured because it is an error, however, this is not recommended because it will make your system unstable.


Start assertions

Assertions are disabled by default. To enable assertions during compilation, use source1.4 to mark both javac source1.4 test. Java and use the-ea parameter to enable assertions during runtime. To enable and disable assertions in the system class, you can use the-ESA and-DSA parameters.

For example:
Public class assertexampleone {
Public assertexampleone (){}
Public static void main (string ARGs []) {
Int x = 10;
System. Out. println ("testing assertion that X = 100 ");
Assert x = 100; "Out assertion failed! ";
System. Out. println ("test passed! ");
}
}

If-source1.4 is not added during compilation, the compilation fails.
When-EA is not added during execution, the output is
Testing assertion that X = 100
Test passed
The JRE ignores the asserted code, and when this parameter is used, the output is
Testing assertion that X = 100
Exception in thread "Main" Java. Lang. assertionerror: Out assertion failed!
At assertexampleone. Main (assertexampleone. Java: 6)


Assertion side effects

Due to programmer problems, the use of assertions may bring side effects, such:
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. It is difficult to find such an error without careful check. At the same time, we can obtain a useful feature based on the above side effects and test whether the assertions are enabled based on it.

Public class assertexampletwo {

Public static void main (string ARGs []) {
Boolean isenable = false;
//...
Assert isenable = true;
If (isenable = false ){
Throw new runtimeexception ("assertion shoule be enable! ");
}
}
}


When to use assertions

1. You can place assert false where the program is not expected to arrive normally.
2. assertions can be used to check the parameters passed to the private method. (For public methods, because they are provided to external interfaces, there must be corresponding parameter checks in the methods to ensure code robustness)
3. Pre-and Post-Conditions for executing the test method using assertions
4. Use assertions to check the unchanged state of the class to ensure that the state of a variable must be met under any circumstances. (For example, the age attribute must be greater than 0 and smaller than a proper value)


Do not use assertion where the statement will not be executed forever. It can be blocked or enabled.
Therefore:
1. Do not use assertion as a parameter check for common methods. Parameters of common methods will always be executed.
2. assertion statements cannot have any boundary effect. Do not use assertion statements to modify variables or change the return values of methods.

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.