Re: Use of AssertionError
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Sun, 30 Dec 2007 21:49:07 -0500
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
.
- References:
- Use of AssertionError
- From: Joshua Cranmer
- Re: Use of AssertionError
- From: Lew
- Re: Use of AssertionError
- From: Daniel Pitts
- Use of AssertionError
- Prev by Date: Re: Great SWT Program
- Next by Date: Re: can't call super from method but I need to??
- Previous by thread: Re: Use of AssertionError
- Next by thread: java data grid
- Index(es):
Relevant Pages
|
|