Re: Exception Names
Tom Anderson wrote:
Later, at some distant point in the code, things go tits-up because of
that null country. Yes, you could add a null check in the constructor,
but that's an extra line of code that has to be remembered to be written.
It still has to be written, although your general discussion of the use case
for exceptions is cogent.
It's a question of invariants, and the notion that a class is written once and
used many times.
If a class design requires that an attribute be not 'null', that is
algorithmically an invariant. Exceptions enforce that invariant. The first
correct place to put such an exception, presumably a runtime exception, is in
the constructor. That way the rest of the code can be written with neither a
'null' check nor an access-time exception.
Invariants can be asserted.
public class Customer
{
private static final Map <Locale, Country> COUNTRIES_BY_LOCALE;
static
{
COUNTRIES_BY_LOCALE = buildCountries();
}
static Map <Locale, Country> buildCountries()
{
Map <Locale, Country> rv = new HashMap <Locale, Country> ();
...
return Collections.unmodifiableMap( rv );
}
private final Country country;
public Customer( Locale locale )
{
this.country = COUNTRIES_BY_LOCALE.get( locale );
if ( this.country == null )
{
throw new IllegalStateException(
new NullPointerException(
"No country for "+ locale.getDisplayName()"
));
}
assert this.country != null; // postcondition
}
public final Country getCountry()
{
assert this.country != null; // precondition
return this.country; // no exception necessary
}
}
--
Lew