- Assertions were introduced in J2SE 1.4
- Rather than introducing it as a class library it was built into the language itself using the keyword assert
- Assertions can be used to test the following three roles:
- Precondition - a condition that the caller of a method agrees to satisfy
- Postcondition - a condition that the method itself promises to achieve
- Invariant - a condition that should always be true for a specified segment or at a specified point of a program
- An assertion has a boolean expression that if evaluated as false indicates a bug in the code
assert a !=b : "Not Equal!!"
- The message part after the : is optional, if given it is passed to the stack trace which is printed
- When an assertion fails, it means that the application has entered an incorrect state
- When the expression evaluates to false an AssertionError is thrown
- A good practice is to terminate the application when the error is thrown, because the application may start functioning inappropriately after a failure
- Assertions are disabled by default - to run an application with assertions enabled we have to give the option "-ea" or "-enableassertion"
java -ea AssertionTest
- The above command enables assertion for all classes except for the system classes
- To turn on assertion in system classes we have to use "-esa" or "-enablesystemassertions"
- To disable assertions we have to use "-da" or "-disableassertion", which is the default
- Also, we can enable or disable assertions for specific classes or packages
java -ea:com.test.ui.UIClass MainClass
java -ea:com.javacourses.tests... -da:com.javacourses.ui.phone MyClass - The ellipsis ... is part of the syntax
- Following is a sample class that uses assertion to check for invalid user input
import java.io.*;
public class AssertionTest {
public static void main(String[] args) throws IOException {
System.out.print("Enter your marital status: ");
int c = System.in.read();
switch((char)c) {
case 's': case 'S':
System.out.println("Single");
break;
case 'm': case 'M':
System.out.println("Married");
break;
case 'd': case 'D':
System.out.println("Divorced");
break;
default:
assert !true : "Invalid Option";
}
}
}
Wednesday, March 11, 2009
How to be assertive
Posted by sathish at 3/11/2009 08:45:00 AM 0 comments
Labels: java
Subscribe to:
Posts (Atom)