Java Reference
In-Depth Information
Tip
Whenassertionsaredisabled,
assert false;
doesnotexecuteandthebug
goes undetected. To always detect this bug, replace
assert false;
with
throw
new AssertionError(direction);
.
Control-Flow Invariants
A
control-flow
invariantisaflowofcontrolthatisnotexpectedtochange.Forexample,
Listing 3-34
uses an assertion to test an assumption that switch's default case will not
execute.
Listing 3-35
, which fixes
Listing 3-34
'
s bug, provides another example.
Listing 3-35.
A buggy control-flow invariant
class CFDemo
{
final static int NORTH = 0;
final static int SOUTH = 1;
final static int EAST = 2;
final static int WEST = 3;
public static void main(String[] args)
{
int direction = (int)(Math.random()*4);
switch (direction)
{
case
NORTH:
System.out.println("travelling
North"); break;
case
SOUTH:
System.out.println("travelling
south"); break;
case EAST : System.out.println("travelling east");
break;
case WEST : System.out.println("travelling west");
default
: assert false;
}
}
}
Because the original bug has been fixed, the default case should ever be reached.
However,theomissionofabreakstatementthatterminates
case WEST
causesexecu-
tiontoreachthedefaultcase.Thiscontrol-flowinvarianthasbeenbroken.(Again,you