最近空閒的時間比較多一些,所以萌起了寫技術文章的念頭,這一部分是我在公司寫的關於Java中assert的介紹與使用。
Assert is a keyword in java, just like for, if, switch, etc. It means assert is a native function in java.
Usage:
int x = 5;
assert x > 4;
If the condition is true, it will do nothing; Otherwise, it will throw java.lang.AsserError and then crash the process.
Note that assert will always be compiled in byte code. It means more you write, then the larger byte code you obtain.
By the way, the assertion mode is disabled in default java command. We need to use parameters to enable it.
Usage:
javac Test.java
java -ea Test <= enable assertion mode
java -da Test <= disable assertion mode
In android, we can use adb command to open assertion mode:
adb shell setprop debug.assert 1 <= enable assertion mode
adb shell setprop debug.assert 0 <= disable assertion mode
Using assert instead of comments is a common way. But we need to be careful not to change the original data and function.
Furthermore, it cannot be used to do error handling because behavior would be changed if assert is disabled.
Example 1:
x = getValue();
/* 20 <= x <= 50 */
Using assert instead of comment:
assert isBetween(x, 20, 50);
private boolean isBetween(int value, int lb. int ub) {
if(value >= lb && value <= ub)
return true;
else
return false;
}
Example 2:
x = 19;
if( x>=20 && x <= 50 )
doSomething(x);
else
throw new Exception(“Not between 20 and 50.”);
Bad codes
x = 19;
assert isBetween(x, 20, 50);
doSomething(x);
The example of snippet shows that if x is not between 20 and 50, it will throw an exception and doSomething(x) is unreachable.
In bad codes, using assert instead of comments will change the original behavior. The function doSomething(x) will always be reached whatever x value if assert is disabled.
As mentioned above, it may obtain the larger byte code because of more assert. However, we can use the if-condition to make assert unreachable in order to avoid this problem.
Usage:
private static final boolean DEBUG = false;
int x = 24;
if(DEBUG) {
assert isBetween(x, 20, 50);
}
Per this method, assert will be removed by code optimization in compilation process.
P.S. We also can use junit assert api for debugging.
http://developer.android.com/reference/junit/framework/Assert.html
沒有留言:
張貼留言