Home >Java >javaTutorial >Detailed explanation of the assert keyword in Java traps
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. Syntax
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 is executing By default, assertion checking is not enabled (at this time, all assertion statements will be ignored!). If you want to enable assertion checking, you need to use the switch -enableassertions or -ea to enable it.
The assert keyword syntax is very simple and has two uses:
1. assert 47931d1e4619fc9f649a93e9e506e8dc
If 47931d1e4619fc9f649a93e9e506e8dc is true, then the program Continue execution.
If it is false, the program throws AssertionError and terminates execution.
2. assert 47931d1e4619fc9f649a93e9e506e8dc : 029e61a2379fe3732f2a9f2558c6adc5
If 47931d1e4619fc9f649a93e9e506e8dc is true, the program continues execution.
If it is false, the program throws java.lang.AssertionError and enters 029e61a2379fe3732f2a9f2558c6adc5.
3. Application examples
The following is an example to illustrate its usage:
public class AssertFoo { public static void main(String args[]) { //断言1结果为true,则继续往下执行 assert true; System.out.println("断言1没有问题,Go!"); System.out.println("\n-----------------\n"); //断言2结果为false,程序终止 assert false : "断言失败,此表达式的信息将会在抛出异常的时候输出!"; System.out.println("断言2没有问题,Go!"); } }
Save the code to C:\AssertFoo.java, and then execute it as follows to view the console output:
1. Compiler:
C:\>javac AssertFoo.java
2. The default execution program is without the -ea switch:
C:\>java AssertFoo
There is no problem with assertion 1, Go!
-----------------
There is no problem with assertion 2, Go!
3. Turn on the -ea switch and execute the program:
C:\>java -ea AssertFoo
There is no problem with assertion 1, Go!
-----------------
Exception in thread "main" java.lang.AssertionError: Assertion failed, the information of this expression will
Will be output when an exception is thrown!
Traps
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 turned on at runtime to take effect, otherwise your assertion will have no meaning. 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, then 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 assert 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 used for debugging test programs and is not used in formal production environments, we should consider better testing JUint to replace its role. , the functions provided by JUint are even better 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 the assertion style, which is very confusing. It is possible that a large number of assertions are used, but I cannot be sure without 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 to write assertions yourself and not use it.
============================================== ================
comment:
can first 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 codes 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
public static List<int> quickSort(List<int> list){ assert list != null; // 申请临时空间 //开始排序 for(int i : list){ // } }
#assert applies to errors that you know what the specific error is, and you and your caller have agreed that your caller should eliminate or check the error. 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 Java uses assert less often is that Java has a very complete OO system and forced type conversions occur less often, 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 the development phase and turned off after release.
For more detailed explanations of the assert keyword in Java traps and related articles, please pay attention to the PHP Chinese website!