Tuesday, December 2, 2008

Assertion

An assertion is a boolean expression that a developer specifically proclaims to be true during program runtime execution. The simple idea of using assertions can have an unexpected influence on a software program's design and implementation.

  • Declare an assertion
    You declare assertions with a new Java language keyword, assert. An assert statement has two permissible forms:
    assert expression1;
    assert expression1 : expression2;
    In each form, expression1 is the boolean-typed expression being asserted. The expression represents a program condition that the developer specifically proclaims must be true during program execution. In the second form, expression2 provides a means of passing a String message to the assertion facility. The following are a few examples of the first form:
    assert 0 < value;
    assert ref != null;
    assert count == (oldCount + 1);
    assert ref.m1(parm);
    The asserted expression must be of type boolean, which the first three expressions obviously are. In the fourth expression, the method call m1(parm) must return a boolean result. A compile-time error occurs if expression1 does not evaluate to type boolean.

  • Enable assertions
    Command-line options to the java command allow enabling or disabling assertions down to the individual class level. The command-line switch -enableassertions, or -ea for short, enables assertions. The switch (I use the short form) has the following permissible forms:
    -ea
    -ea:
    -ea:...
    -ea:...

  • Class AssertionError
    The new assertion facility adds the class AssertionError to the java.lang package. AssertionError contains a default constructor and seven single-parameter constructors. The assert statement's single-expression form uses the default constructor, whereas the two-expression form uses one of the seven single-parameter constructors.
    To understand which AssertionError constructor is used, consider how assertions are processed when enabled:
    Evaluate expression1
    If true
    No further action
    If false
    And if expression2 exists
    Evaluate expression2 and use the result in a single-parameter form of the AssertionError constructor
    Else
    Use the default AssertionError constructor
  • Since the assert statement in class Foo uses the single-expression form, the violation triggered in passing -1 to method m1(int) prompts the use of the default AssertionError constructor. The default constructor effectively uses java.lang.Throwable's default constructor to print an exception message that includes a textual stack trace description.

0 comments: