[View INPRISE Home Page][View Product List][Search This Web Site][View Available Downloads][Join Inprise Membership][Enter Discussion Area][Send Email To Webmaster]
INPRISE Online And ZD Journals Present:



Implementing assertions in JBuilder
By Qusay H. Mahmoud

Classes in an OOP language should be known not only by the methods they provide, but also by the behavior and formal properties of these methods. The Eiffel programming language, for example, encourages programmers to express class behaviors by writing assertions that may appear in the following roles:

  • Precondition—a condition the operation's caller agrees to satisfy (EiffelÆs require keyword)
  • Postcondition—a condition the method itself promises to achieve (EiffelÆs ensure)
  • Invariant—a condition a class must satisfy at all times (EiffelÆs invariant)

These three roles collectively support the contract model of programming. Java, on the other hand, doesn't have built-in support for the contract model of programming. Actually, Java doesn't even have built-in support for assertions. In this article, we'll show you how to implement assertions in JBuilder.

About assertions
An assertion is a boolean expression that, if evaluated as FALSE, indicates a bug in the code. This feature provides a mechanism to detect when a program starts falling into an inconsistent state. Assertions also let you document class assumptions and invariants. Using assertions helps you write code that's easier to read and maintain—thus, you 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 assert will be executed only when the macro NDEBUG is undefined. The program will abort if expression evaluates to false (0); if expression evaluates to true (non-0), assert has no effect. For performance reasons, however, you should write assertions into software in a form that you can optionally compile. Thus, you'll execute assertions with the code only when you're in the debugging stage of software development—where assertions will really help in flushing out errors.

Implementing assertions
You can implement assertions in Java quite nicely. First, create a new exception class for your assertions class, as follows:

AssertionException.java
public class AssertionException extends
  RuntimeException {
    public AssertionException() { super(); };
    public AssertionException(String msg) { 
      super(msg); 
    }
  }

This code extends RuntimeException.

Basically, the two kinds of exceptions are checked and unchecked. Java organizes the possible exceptions 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. The RuntimeException class is a direct subclass of Exception. 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. This simplifies your job by not requiring you to declare such exceptions, which could be an irritating process.

The following code implements an assert method:

Assert.java
public class Assert {
  public static boolean NDEBUG = true;
  public static boolean assert(
    boolean expression) 
  throws AssertionException {
    if (NDEBUG && !expression) {
      throw new AssertionException();
    }
  return true;
  }
}

The assert method 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 the previous code snippet), will be thrown; otherwise, nothing happens.

Note that in the assert method you also check whether the value of NDEBUG (which is boolean) is on or off. If NDEBUG is on (set to true), then the assertion is to be executed; otherwise it should have no effect. Clients who use the Assert class should be able to change the value of NDEBUG from their own programs.

Listing A provides a very simple demonstration of how to use this 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 turns off the execution of assertions.

Listing A: Implementing the assert class

TestAssertion.java
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 above line to turn off assertions 
    Assert.assert(n>0);
    // use n 
  }
}

If you run the program in Listing A, 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—it won't be incremented if Assert.NDEBUG is set to false!


Quinsay H. Mahmoud is a graduate student in computer science at the University of New Brunswick, Saint John, N.B., Canada. For his thesis, he implemented a distributed computing system over the Web using Java. You can reach him online at qusay@garfield.csd.unbsj.ca.
Back to Top
Back to Index of Articles

Copyright © 1997, ZD Journals, a division of Ziff-Davis Inc. ZD Journals and ZD Jounals logo are trademarks of Ziff-Davis Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis is prohibited.
Trademarks & Copyright © 1998 INPRISE Corporation.