Asserts in Java
Preamble
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:
- Minimize execution impact
- For messages composed of compound strings, don't perform concatenation
unless the condition fails
- Turn off checking of asserts to improve runtime performance
The last goal could be accomplished by either of these methods:
- Use a quick check of a boolean to short circuit more complicated checks
- Conditional compilation
- Some complex scheme involving multiple classes that are the same except
for checking code
Implementing asserts in Java without changing the language:
A basic implementation:
if (!(assertcondition))
throw new IllegalArgumentException("myvariable is illegal:" +
myvariable);
Using the quick check:
if (Assert.on && !(assertcondition))
throw new IllegalArgumentException("myvariable is illegal:" +
myvariable);
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.