HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Program correctness may be viewed as proof that the computation, given correct input, terminated with correct output. The person who invokes the computation has the responsibility of providing the correct input, which is a precondition. If the computation is successful, we say that the computation has satisfied the postcondition. The Eiffel programming language (www.eiffel.com) for example, encourages programmers to provide a fully formal proof of correctness by writing assertions that may appear in the following roles:

  • Precondition - a condition an operation's caller agrees to satisfy. In Eiffel the keyword require introduces a precondition.
  • Postcondition-- a condition that the method itself promises to achieve. In Eiffel the keyword ensure introduces a postcondition.
  • Invariant-- a condition that a class must satisfy at all times. The invariant keyword introduces an invariant in Eiffel.
These three roles collectively support what is called the contract model of programming, a model that's well supported by the Eiffel programming language. Java, on the other hand, doesn't have built-in support for this model. Actually, Java doesn't even have built-in support for assertions. However, Java has a far superior feature to assertions - exception handling (see the Java tutorial on JavaSoft, "Handling Errors with Exceptions," for details).

C-Style Assertions
An assertion is a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state. Assertions are also excellent for documenting assumptions and invariants about a class. Using assertions helps programmers write better code in terms of correctness, readability and maintainability. Thus they improve the odds that the behavior of a class matches the expectations of its clients.

In C/C++ you can use assertions through assert. In ANSI C, assert has the following definition:

void assert(int expression)

The assertion will be executed only when the macro NDEBUG is undefined. The program will be aborted if the expression evaluates to false (0); if the expression evaluates to true (non-0), assert has no effect. For performance reasons, however, you should write assertions into software in a form that can be optionally compiled. Thus assertions should be executed with the code only when you're in the debugging stage of software development -- that's where assertions will really help in flushing out errors. Note: Assertions represent a uniform methodology that replaces the use of ad hoc conditional tests.

Implementing Assertions in Java
You can implement assertions in Java quite nicely. First, create a new exceptions class for your assertions class, as shown in Listing 1.

Listing 1 extends RuntimeException, a direct subclass of Exception. Basically, there are two kinds of exceptions: checked and unchecked. The possible exceptions in Java are organized in a hierarchy of classes rooted at class Throwable, which is a direct subclass of Object. The classes Exception and Error are direct subclasses of Throwable. Instances (and subclasses) of Error and RuntimeException are called unchecked exception(s) (classes).

In checked exceptions the Java language checks at compile time whether a Java program contains handlers for exceptions. However, unchecked exceptions (as in RuntimeExceptions) are excluded from this checking. Thus Java simplifies the programmer's task by not requiring you to declare such exceptions, which could be an irritating process.

The code in Listing 2 implements an assert method, which takes a Boolean expression as an argument and checks whether it's true or false.

If it's false, your new exception, AssertionException (declared in Listing 1), will be thrown; otherwise nothing happens. Note that in the assert method you're also checking whether the value of NDEBUG (which is Boolean) is on or off. If it's on (set to true), then the assertion is to be executed; otherwise it should have no effect. Also note that clients who use the Assert class should be able to change the value of NDEBUG from their own programs.

Listing 3 provides a simple demonstration of how to use the Assert class. If you don't want assertions to be executed as part of the code, you could declare the line:

Assert.NDEBUG = false

which is really an easy way of turning off the execution of assertions. If you run the program in Listing 3, you'll see the following output:

% java TestAssertion
Please input a number: -1
AssertionException
at Assert.assert(Assert.java:5)
at TestAssertion.main
(TestAssertion.java:15)

A word of caution: never use the Assert class expression that involves side effects. Writing

Assert.assert(++i > 0)

for example, isn't a good idea, because the variable i won't be incremented if Assert.NDEBUG is set to false!

The Downside of Assertions
The use of assertions replaces the ad hoc use of conditional tests with a uniform methodology. This methodology doesn't allow for a repair strategy to continue program execution, however. This means that when an exception is detected, the program aborts with no recovery mechanism. This is certainly preferable to undefined behavior when something goes wrong, but it's unacceptable for a wide variety of applications. For example, a program that acquires resources (e.g., a lock on a database) shouldn't be allowed to abort without releasing those resources. A superior feature to assertions is built into Java - exception handling. It's superior in the sense that it allows you, using try/catch/finally, to throw an exception object instead of aborting.

Conclusion
When writing programs, you'll find it's a good idea to put checks at strategic places for violations of basic assumptions. These checks help in debugging code. The Assert class implemented in this article provides a convenient way for programmers to abort Java programs while printing a message stating where in the program the error was detected. Remember, these messages are for us - the programmers - not for users. Exception handling in Java is a superior methodology for handling errors when something goes wrong.

About the Author
Qusay works for Etisalat College of Engineering, UAE. Previously he worked for Newbridge Networks and Carleton University, both in Canada. Qusay is the author of an upcoming book on distributedprogramming with Java. You can reach him at [email protected]

	

Listing 1: An Exceptions Class

/**
*AssertionException.java
* @author Qusay H. Mahmoud, [email protected]
*/
AssertionException.java public class AssertionException extends
RuntimeException { public AssertionException() {
super(); }; public AssertionException(String msg) {
super(msg); } } 

Listing 2: An Assert Method

/**
*Assert.java
* @author Qusay H. Mahmoud, [email protected]
*/
Assert.java public class Assert { public static boolean NDE-BUG
= true; public static boolean assert( boolean
expression) throws AssertionException { if
(NDEBUG && !expression) { throw new AssertionExcep-
tion(); } return true;
} }

Listing 3: Implementing the Assert Class

/**
*Test Assertion.java
* @author Qusay H. Mahmoud, [email protected]
*/
import java.io.*; public class TestAssertion { public static
void main(String argv[]) { BufferedReader is = new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input a number: ");
System.out.flush(); String ans=null;
try { ans = is.readLine(); }
catch(IOException e1) { System.out.println("Error:
"+e1); } int n = Integer.parseInt(ans);
// Assert.NDEBUG = false; // Uncomment the above line
// to turn assertions off.
Assert.assert(n > 0); // Use n. }
}
      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.