Internal Invariants

An internal invariant is expression-oriented behavior that is not expected to change. For example, Listing 5-3 introduces an internal invariant by way of chained if-else statements that output the state of water based on its temperature.

Listing 5-3. Discovering that an internal invariant can vary public class IIDemo {

public static void main(String[] args) {

double temperature = 50.0; // Celsius if (temperature < 0.0)

System.out.println("water has solidified"); else if (temperature >= 100.0)

System.out.println("water is boiling into a gas");

// temperature > 0.0 and temperature < 100.0 assert(temperature > 0.0 && temperature < 100.0): temperature;

System.out.println("water is remaining in its liquid state");

A developer might specify only a comment stating an assumption as to what expression causes the final else to be reached. Because the comment might not be enough to detect the lurking < 0.0 expression bug, an assertion statement is necessary.

Another example of an internal invariant concerns a switch statement with no default case. The default case is avoided because the developer believes that all paths have been covered. However, this is not always true, as Listing 5-4 demonstrates.

Listing 5-4. Another buggy internal invariant public 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) {

switch (direction)

System.out.println("travelling north"); break; System.out.println("travelling south"); break; System.out.println("travelling east"); break; System.out.println("travelling west"); break; assert false;

case NORTH: case SOUTH: case EAST case WEST default

Listing 5-4 assumes that the expression tested by switch will only evaluate to one of four integer constants. However, (int)(Math.random()*5) can also return 4, causing the default case to execute assert false;, which always throws AssertionError. (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.)

TIP: When assertions are disabled, assert false; does not execute and the bug goes undetected. To always detect this bug, replace assert false; with throw new AssertionError(direction);.

Was this article helpful?

0 0

Post a comment