4. In-line Assertions

The assert keyword was introduced into the Java language to allow invariants to be asserted within production code. To quote the Java guide:

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.

The Sureassert UC Engine runs all Exemplars and JUnits with assertions enabled. Any assert failures are added as Sureassert error markers at the line of the assert statement.

Often in-line assert statements are overlooked in favour of asserting state within JUnit methods. This can potentially have the effect of reducing maintainability as the rules around invarients that govern your code are not placed within the code itself. Consider using assert statements with Exemplars: this can be a powerful combination.

For more information see http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html

Previous Page   |   Next Page   |   Table of Contents

Comments are closed.