Asserts in Java


I keep going back and forth on whether Asserts would be a good thing in Java. The "Design by Contract" idea is rather compelling, but the need to add them to the language and the question of what to do during runtime when a problem occurs remain a problem.

Purpose of Asserts:

Provide a mechanism for explicitly checking (asserting) part of a program's state at runtime to detect problems in code. Typically a programmer is able to specify a message to be displayed when the condition fails.

Goals of assert implementation include:

The last goal could be accomplished by either of these methods:

Implementing asserts in Java without changing the language:

A basic implementation:
  if (!(assertcondition))
    throw new IllegalArgumentException("myvariable is illegal:" +
Using the quick check:
  if (Assert.on && !(assertcondition))
    throw new IllegalArgumentException("myvariable is illegal:" +
Syntactic sugar that makes these statements more concise could be achieved by running the code through a preprocessor. This could allow a mode of compilation that totally removes the exception code.

Changing the Java language to support assert:

This could be done by adding a generic preprocessor or a specialized preprocessor. Either way, the resulting code that is generated would be effectively equivalent to implementing asserts without changing the language.

Given this, the only advantage to be gained by adding support for asserts into the language is syntactic sugar; its addition would thus bloat the language with perhaps one source code line savings per usage.

Last updated on Saturday, 18-May-2002 09:13:47 MDT.
You are visitor [an error occurred while processing this directive] since 05 April 1998.