Another good candidate for an assertion is a switch statement with no default case.
For example:
switch(suit) {
case Suit.CLUBS:
...
break;
case Suit.DIAMONDS:
...
break;
case Suit.HEARTS:
...
break;
case Suit.SPADES:
...
}
|
The programmer probably assumes that one of the four cases in the above switch statement will always be executed. To test this assumption, add the following default case:
default:
assert false;
|
More generally, the following statement should be placed at any location the programmer assumes will not be reached.
assert false; |
For example, suppose you have a method that looks like this:
void foo() {
for (...) {
if (...)
return;
}
// Execution should never reach this point!!!
}
|
Replace the final comment with:
assert false; |
Note, use this technique with discretion. If a statement is unreachable as defined in (JLS 14.19), you will see a compile time error if you try to assert that it is unreached.