Re: Use of AssertionError



Daniel Pitts wrote:
How about this case:

public String getSomethingRandom() {
final int value = random.nextInt(3);
switch (value) {
case 0:
return "Nothing here.";
case 1:
return "Got something!";
case 2:
return "Twice the fun?";
default:
throw new AssertionError("Something wrong!");
}
}

This seems like a good case for assertions, except for that disabling asserts doesn't disable explicit throws like this one. It's a little simplistic, but it does illustrate an invariant.

Here's more of a realistic use case for assert: replace the literal '3' with a variable coming from a private source, that should have been constrained to less than APP_MAXRAND. Put the whole violated condition in the assert:

public String getSomethingRandom()
{
final int value = random.nextInt( somePrivateMethod() );

// The assert really belongs here, but it's more fun below.
// It belongs here because here is where the invariant should hold.

switch ( value )
{
case 0:
return "Nothing here.";
case 1:
return "Got something!";
case 2:
return "Twice the fun?";
default:
assert value >= 0 && value < APP_MAXRAND;
throw new IllegalStateException( "Invalid random value "+ value );
}
}

--
Lew
.



Relevant Pages