Wednesday, March 11, 2009

How to be assertive

  • 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
    1. 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"
    1. 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
    1. java -ea:com.test.ui.UIClass MainClass  
    2. 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
    1. import java.io.*;  
    2.   
    3. public class AssertionTest {  
    4.  public static void main(String[] args) throws IOException {  
    5.      System.out.print("Enter your marital status: ");  
    6.      int c = System.in.read();  
    7.      switch((char)c) {  
    8.          case 's'case 'S':  
    9.              System.out.println("Single");  
    10.              break;  
    11.          case 'm'case 'M':  
    12.              System.out.println("Married");  
    13.              break;  
    14.          case 'd'case 'D':  
    15.              System.out.println("Divorced");  
    16.              break;  
    17.          default:  
    18.              assert !true : "Invalid Option";  
    19.      }  
    20.  }  
    21. }