|
SYS-CON.TV Webcasts
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
Top Links You Must Click On
General Java Implementing Assertions in Java
Implementing Assertions in Java
Dec. 1, 1997 12:00 AM
Any software system, whether object-oriented or not, relies on the state of the system being "correct" at certain stages of its execution. To take a very simple example, when a numerical division operation is performed, the divisor must be non-zero. If this is not the case, the system may crash in an unpredictable and uncontrolled manner. One way of indicating such requirements is to state that the system must be in some state either before or after an operation. Such a statement about the state of a software system is called an assertion. Assertions often form the basis for software specification. In some systems, the assertions are embedded in the software as annotations or formal comments. However, it can be useful to make the assertions executable so that the correctness of the system is checked at runtime. A simple technique is to make the code do its own self-testing using a method call and a programming languages exception mechanism. The code checks that the statement passed to it is true, thus allowing it to test that the code is behaving as expected. If the statement is false, the method uses an exception to stop processing, thereby enabling debugging. This article looks at how assertions can be implemented within the Java programming language [1]. In the remainder of this article, we introduce the concept of assertions, how they can be used and how they can be implemented. In particular, we introduce two types of assertions: one which generates a runtime exception if it fails and one which generates a checked exception (which must be handled by the programmer) if it fails. We then provide a brief analysis of the facilities provided by this approach.
Assertions and Their Uses Programming languages have been developed which enable assertions to be embedded into the code itself, for example Gypsy [5] or SPARK [3, 2]. Tools available with these language systems enable the assertions to be checked and, in some cases, proved. Another approach is to introduce assertions into existing programming languages by using formal comments, called annotations, or by pre-processing. The C programming language has been extended with annotations[7] and Ada has been similarly extended into Anna [11]. An annotation pre-processor for C is described in Rosenblum's "A Practical Approach to Programing with Assertions" [13]. In these systems, tool support enables the assertions to be checked against the program code. However, extra-language syntax is required and, in the case of annotations, the assertions are lost when the program is compiled. It may be better to have assertions as part of the code so that they provide a permanent defensive programming mechanism for detecting faults at runtime [12]. The exception mechanism of a programming language can be used for this [8]. In the following sections we show how this can be done for Java.
Using Assertions in Java The difference between the checked and the non-checked assertions for the developer is that they must explicitly handle any exceptions raised by the CheckedAssertion class, whereas they can choose to ignore the fact that an exception may be raised by the Assertion class. In Java, a package is an associated group of classes and interfaces [1]. We have defined a new package assertion which holds the four classes listed above. Other classes can then use these four by importing the assertion package. An example of how these classes are used is presented in Listing 1. This example creates a simple class Example which uses the Assertion class to handle the result of checking the relationship between a and b. The result of running this application is presented in Listing 2. We could have caught the AssertionException within a try{} catch{} block. This construct allows a piece of code to be wrapped up within a try block. The try block indicates the code which is to be monitored for the exceptions listed in the catch expressions. The catch expressions can then be used to indicate what to do when certain classes of exception occur; for example, "resolve the problem" or "generate a warning message", etc. If no catch expressions are included the throws clause must be handled by the method definition. For example:
try { e.test(1, 2);
Exceptions in Java The class Throwable has two subclasses, Error and Exception. Errors are unchecked exceptions. These are exceptions which your methods are not expected to deal with. The compiler therefore does not check that the methods can deal with them. In contrast, most exceptions (but not RuntimeException and its subclasses) below the class Exception are checked exceptions. These exceptions must be dealt with by your methods. The compiler thus checks to see that methods throw only exceptions which they can deal with (or are passed up to other methods to handle). For example, if we wished to raise an ArithmeticException, for a divide by zero error then we would write: throw new ArithmeticException("Division By Zero"); In Java, you are not limited to system-provided exceptions; it is also possible to provide user-defined exceptions. This can be very useful as such an approach can allow the developer to have more control over what happens in particular circumstances. To do so, a developer must subclass the Exception class or one of its subclasses.
Assertions in Java The second method is really a convenience method which repeatedly calls the first method on each element in the array. The implementation of the assert(boolean bool) method is relatively straightforward. The method checks whether the boolean value is false or not. If it is false an exception is raised. The assert(boolean bools []) method simply calls the previous method iteratively (see Listing 3).
Switching Assertion Checking Off
public static void assert (boolean bool) throws AssertionException { As Java dynamically loads the appropriate .class file at runtime, we could distribute the final version of the system with an Assertion.class file based on the above implementation of assert. We would therefore not even need to recompile the system being released. The overhead of the extra method dispatch is relatively small; of course, if it is still significant we could write a utility to find the senders of the assert method and to comment out the assertion statements.
The AssertionException class
CheckedAssertion and CheckedAssertionException The advantage is that the developer using the assertions can decide how much control to give to the user of a component. If they wish, they can force that user to handle the exception and thereby allow them to take charge of any problems which occur. This can result in code which is more resilient to erroneous situations. For completeness, the two classes are presented in Listings 5 and 6.
Analysis
JavaBeansª
Shortcomings
void swap (SomeType x, SomeType y) {
One might want to assert, just before the method returns, that the new value of x is equal to the old value of y and the new value of y is equal to the old value of x. This is not possible with our assertion mechanism. Assertion mechanisms for which this is possible have additional syntax which allows the "before and after" values of variables to be distinguished.
Conclusions We have demonstrated a simple mechanism for introducing assertions into Java programs. Two classes have been defined: Assertion and CheckedAssertion. The former allows assertions to be used very simply. Any exceptions thrown as a result of the assertions failing may be caught or propagated out of the program. The CheckedAssertion class requires the exceptions to be caught or explicitly listed in a throw clause for the methods involved. This provides greater control and "self documentation" of the assertion mechanism. Our assertion mechanism is particularly valuable when Java is used in larger, critical applications, where developers are implementing classes for general use and for Java Beans components.
References Reader Feedback: Page 1 of 1
Enterprise Open Source Magazine Latest Stories . . .
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||