Saturday 4 January 2014

Working with Java Assertion


Java Assertion or assert keyword in java 
 is little unknown and not many programmer is familiar with this and it's been rarely used specially if you have not writing unit test using JUnit which extensively uses Java assertion to compare test result.
Assertion not only improve stability of code but also help you to become better programmer by forcing you to think about different scenario while writing production quality code and improving your think through ability.
Test your assumptions during development.
Always assert that something is true.
AssertionError is thrown.
Disable by default.
Two different methods:
·         assert     (y > x);
·         assert     (y > x): “y is “+y+” x is “+x;

We were not supposed to make assumptions, but we can’t help it when we’re writing code.
if (x > 2 && y) {
// do something
} else if (x < 2 || y) {
// do something
} else {
// x must be 2
// do something else
}
You write print statements with them:
while (true) {
if (x > 2) {
break;
}
System.out.print(“If we got here something went horribly wrong”);
}
     Added to the Java language beginning with version 1.4, assertions let we test our
assumptions during development, without the expense (in both your time and program overhead) of writing exception handlers for exceptions that we assume will never happen once the program is out of development and fully deployed.

java -ea com.testing.TestClass
or
java -enableassertions com.testing.TestClass
java -da com.testing.TestClass
or
java -disableassertions com.testing.TestClass
no arguments
package names
class names
Don’t use assertions to validate arguments to a Public Method.
Use assertions to validate arguments to a Private Method.
Don’t use to validate command-line arguments.
Don’t use assert expressions can cause side effects.


No comments:

Post a Comment