Java Reference
In-Depth Information
Anotherexampleofaninternalinvariantconcernsaswitchstatementwithnodefault
case.Thedefaultcaseisavoidedbecausethedeveloperbelievesthatallpathshavebeen
covered. However, this is not always true, as Listing 3-34 demonstrates.
Listing 3-34. Another buggy internal invariant
class IIDemo
{
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() *5 );
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");
break;
default
: assert false;
}
}
}
Listing 3-34 assumes that the expression tested by switch will only evaluate to one
offourintegerconstants.However, (int) (Math.random()*5) canalsoreturn4,
causingthedefaultcasetoexecute assert false; ,whichalwaysthrows Asser-
tionError . (You might have to run this application a few times to see the assertion
error, but first you need to learn how to enable assertions, which I discuss later in this
chapter.)
 
Search WWH ::




Custom Search