1. Overview
There is the assert key in C and C++ languages, which means assertion.
In Java, there is also the assert keyword, which means assertion. The usage and meaning are similar.
2. Grammar
In Java, the assert keyword was introduced from JAVA SE 1.4. In order to avoid errors caused by using the assert keyword in older versions of Java code, Java does not enable assertion checking by default when executing (at this time, all Assertion statements will be ignored!), if you want to enable assertion checking, you need to turn it on with the switch -enableassertions or -ea.
The assert keyword syntax is very simple and has two uses:
1. assert <boolean expression>
If <boolean expression> is true, program execution continues.
If false, the program throws an AssertionError and terminates execution.
2. assert <boolean expression>: <error message expression>
If <boolean expression> is true, program execution continues.
If it is false, the program throws java.lang.AssertionError and enters <error message expression>.
3. Application examples
An example is given below to illustrate its usage:
Copy the code code as follows:
public class AssertFoo {
public static void main(String args[]) {
//The result of assertion 1 is true, then continue execution.
assert true;
System.out.println("There is no problem with assertion 1, Go!");
System.out.println("/n-----------------/n");
//The result of assertion 2 is false and the program terminates
assert false : "Assertion failed, the information of this expression will be output when an exception is thrown!";
System.out.println("There is no problem with assertion 2, Go!");
}
}
Save the code to C:/AssertFoo.java, then execute it as follows and view the console output:
1. Compile program:
C:/>javac AssertFoo.java
2. The program is executed by default without turning on the -ea switch:
C:/>java AssertFoo
Assertion 1 is fine, Go!
------------------
Assertion 2 is no problem, Go!
3. Turn on the -ea switch and execute the program:
C:/>java -ea AssertFoo
Assertion 1 is fine, Go!
------------------
Exception in thread "main" java.lang.AssertionError: Assertion failed, the information of this expression will
Will be output when an exception is thrown!
at AssertFoo.main(AssertFoo.java:10)
4. Trap
The assert keyword is simple to use, but using assert will often make you fall into a deeper and deeper trap. Should be avoided. After research, the author summarized the following reasons:
1. The assert keyword needs to be explicitly enabled at runtime to take effect, otherwise your assertion will be meaningless. Currently, mainstream Java IDE tools do not enable the -ea assertion checking function by default. This means that if you use IDE tools to code, you will have some trouble when debugging and running. Moreover, for Java Web applications, the program code is deployed in the container, and you cannot directly control the running of the program. If you must turn on the -ea switch, you need to change the running configuration parameters of the Web container. This brings great inconvenience to the transplantation and deployment of programs.
2. Using assert instead of if is the second trap. The judgment of assert is similar to that of if statement, but the functions of the two are essentially different: the assert keyword is intended to be used when testing and debugging the program, but if you accidentally use assert to control the business process of the program, it will not be used during testing and debugging. Removing the assert keyword after completion means modifying the normal logic of the program.
3. If the assert assertion fails, the program will exit. This would never be tolerated in a production environment. Potential errors in the program are generally solved through exception handling. But using assertions is very dangerous. Once it fails, the system will hang.
5. Thoughts on assert
Since assert is for debugging test programs and not for use in formal production environments, you should consider better testing JUint to replace its function. JUint provides even more key functions than assert. Of course, debugging and testing can be carried out through IDE debug. From this point of view, the future of assert is bleak.
Therefore, you should avoid using the assert keyword in Java, unless one day Java supports the -ea switch by default, then you can consider it. Compare how much benefit and how much trouble assert can bring you. This is the principle for us to choose whether to use it.
================================================== ==========
comment:
On the other hand, in some open source components, such as validator and junit, the judgment process seems to use an assertion style. It is very likely that a large number of assertions are used, but the author cannot be sure before looking at the source code.
If it is a simple test during the development phase, junit is a convenient and powerful tool. There is no reason not to use it when writing your own assertions.
================================================== ==========
comment:
First it can be used in unit test code. Junit is very intrusive. If a large amount of code in the entire project uses Junit, it will be difficult to remove it or choose another framework. If there are a lot of unit test codes and you want to reuse these unit test cases, you should choose assert instead of junit to facilitate the use of other unit test frameworks, such as TestNG. For the same reason, Junit should not appear in formal functional code at all, and assert should be used.
assert is mainly suitable for base classes, framework classes, interface classes, core code classes, and tool classes. In other words, it is necessary to use it when the caller of your code is business code written by another programmer, or another subsystem. For example, if you make a quick sort algorithm
Copy the code code as follows:
public static List<int> quickSort(List<int> list){
assert list != null;
//Apply for temporary space
//Start sorting
for(int i : list){
//
}
}
In this case, if the correctness of the incoming parameters is not checked, an inexplicable null pointer error will be thrown. Your callers may not know the details of your code, and debugging a null pointer error deep in a system is a waste of time. You should directly and clearly tell your caller that there is a problem with the parameters passed in. Otherwise, he will suspect that your code has a BUG. Using assert can prevent two programmers from blaming each other for problems with the code they wrote.
assert applies to errors that you know exactly what the error is, and you and your caller have agreed that your caller should eliminate or check for errors. You tell your caller via an assertion. assert does not apply to errors caused by external systems, such as errors in user input data or format errors in an external file. These errors are not caused by your caller but by the user, and are not even exceptions, because input errors and file format errors are common, and these errors should be checked by the business code.
assert is more suitable for frequently called base classes, framework code, tool classes, core code, and interface code. This is why it is removed at runtime. The test code should enable the -ea parameter during the testing phase to facilitate careful testing of the core code deep in the system.
The reason why Java uses assert less often is that Java has a very complete OO system and forced type conversion occurs less frequently, so there is no need to frequently check whether the type of the pointer is correct and whether the pointer is empty like C. At the same time, Java rarely manages memory or buffers directly, so there is no need to frequently check whether the incoming buffer is empty or has crossed the boundary.
But using assert well can help improve the correctness of the framework code and reduce the debugging time of users of the framework code.
================================================== =============
comment:
The purpose of assert is to allow programmers to easily discover their own logic errors without affecting the efficiency of the program. The errors found by assert should not occur at all and cannot be replaced by exceptions. Exceptions are allowed by the system, or are "errors" that are uncontrollable by the system. They are not logical problems of the programmer.
assert should be turned on during development and turned off after release.