Assertions in Java
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
if
statement (e.g., that throws
an exception) if the assumption doesn't holdassert boolean_expression;
assert boolean_expression : expression;
-enableassertions
(or -ea
)
switch to enable and/or the
-disableassertions
(or -da
)
switch to disable
This fragment assumes i
is non-negative.
if (i > 0) { // Do something } else // We know i is equal to 0 { // Do something }
One Approach:
if (i > 0) { // Do something } else { assert i == 0 : i; // Do something }
Another Approach:
assert i >= 0 : i; if (i > 0) { // Do something } else { // Do something }
The Original Code Ignoring the Invariant:
if (delta > 0) total += delta;
Alternative Code Ignoring the Invariant:
total += Math.max(0, delta);
Taking Advantage of the Invariant Using an Assertion:
assert delta >= 0 : delta; total += delta;
This fragment assumes that there are only four suits.
switch(suit) { case Suit.CLUBS: // Do something break; case Suit.DIAMONDS: // Do something break; case Suit.HEARTS: // Do something break; case Suit.SPADES: // Do something break; default: // Shouldn't get here }
Using an assertion
switch(suit) { case Suit.CLUBS: // Do something break; case Suit.DIAMONDS: // Do something break; case Suit.HEARTS: // Do something break; case Suit.SPADES: // Do something break; default: assert false : suit; }