Assertion
Java have an “assert” keyword since java 1.4
Usage
There are two kinds of syntax:
-
assert expression1
-
assert expression1 : expression2
expression1 must be evaluated as boolean ( true or false) while expression2 can be primitive, object, or array.
expression2 is passed into the constructor of AssertionError as an argument.
So if expression2 is evaluated as void, it’s not allowed.
void foo() {}
assert true : foo(); // cannot be compiled
How to enable or disable assertion
Assert statements will be evaluated only if assertion is enabled.
- through command options (aka. VM options)
ClassLoader class has some methods related to assertion setting:
Some restrictions and pitfalls
- assertion and inheritance
The following is an example:
class Derived extends Base {
public void derivedMethod() {
assert false : "Assertion failed:This is derive";//assertion always fails
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);
}
}
}
Now we use all kinds of command options and see the output results:
Best/bad usage scenarios
- it’s preferable to assert the arguments of private method.
You should not use assertions to check arguments in public methods because it would otherwise throw runtime exceptions: IllegalArgumentException, NullPointerException, and so forth.
- it’s BAD flavour that assertion has some side effects
private int a = 1;
private String foo() {
a = 4;
return "sss";
}
private void assertSomething() {
assert false : a++; // This has a side effect
assert false: foo(); // This also has a side effect
}
As assertion can be disabled, so there will be something strange to happen if you do something depending on assertion fails.
In the above example, if assertion is disabled, then the variable will be unchanged.
- in if-then-else and swith-case flow-control statements, you can add “assert false;” in unexpected branch of control.
switch(x) {
case 1: …;
case 2: …;
case 3: …
default: assert false : "x value is invalid: " + x;
}
if(a==1) {
// some codes here
} else if {
// some codes here
} else {
assert false : "Normally, it cannot be here";
}
This is a defensive technology when you do some test. We can generalize this good style into other similar cases, for example, when you think some place in your code will never be reached. In these cases, the assertion is very useful, because once the assertion fails, there will be something critical logic errors or some programming faults.
4) You should not use assertions to validate your business logic and avoid using assertions to check or validate method arguments.