Java's new assertion mechanism, a welcome addition to the language now
available in version 1.4, allows programmers to increase the robustness of
their code by sprinkling it liberally with assert statements. The new
assertion feature is easy to use, but any language feature, no matter how
simple, can be used well or poorly. Here I'll explain how to use Java's
assertion facility, and how not to misuse it.
Using assertions couldn't be easier. Anywhere you can put a statement in
Java, you can now write
assert boolExpr;
where boolExpr is any Boolean expression. If the expression is true,
execution continues as if nothing happened. If it's false, an exception is
thrown. You can disable assertions at runtime if you wish, effectively
removing them from your code.
Why Use Assertions?
Assertions are a cheap and easy way of building confidence in your code. When
you write a... (more)