11 April 2012

Assertions in Java

Assertion is a feature of Java that enables to have contract compatibility controls and assumption tests which can be simply enabled in any time for problem tracking in code. Assertions can be simply implemented and makes easy to find the cause of problems, if it is properly used in error prone points of code.

Method parameters has specific expectations and limitations in API documentation. Thus, assertion with method parameters are generally used to detect problems with appropriate expressions. For example:

public class XFileReader {
  public XFileReader(String fileName) {
    // fileName cannot be null or empty string
    assert fileName != null || fileName.equals("") : 
       "XFileReader cannot be initiated with fileName="+fileName;
    // ... constructing XFileReader
  // ... file reading related code goes here
  public String readLine(int lineNumber) {
    // simple assertion without an expression, 
    // only java.lang.AssertionError with related code line numberis printed in SystemOut.log
    assert lineNumber < 0;

    // related implementation goes here

Purposely, java.lang.AssertionError is subclass of java.lang.Error and it is not an exception. Because, assertion exception might be caught and dismissed by mistake and the cause of problem cannot be detected, otherwise. I think that as opposed to declaring an IllegalArgumentException in a method, assertions with clear expressions is the only strict way of finding bugs in critical code blocks.

Take Care...