Roedy Green said:
A way you can get a sort of quasi type safety you see in the AWT with
the GridBag constants. Different types of enums are given different
RANGES of values. Then you can check that the right sort of enum
constant was given with a simple check of this form:
if ( ! (SMALLEST_FRUIT <= fruit && fruit <= BIGGEST_FRUIT) )
{
throw new IllegalArgumentException ( "fruit " + fruit + " not a valid
fruit enumerated type." );
}
You assign each of your enums non-overlapping but dense ranges.
There is more to the issue than just type safety.
In your example, you have immediate runtime failure in the event of a
misuse.
The alternative without the check is some indeterminate behaviour - allowing
the application to carry on with a bad value.
More preferred is compile-time failure, which is provided by the type-safe
enumeration design pattern.
A further issue is the fact that a "public static final int [or other
appropriate type - JLS 15.28]" that is not "lazily initialised" is a
compile-time constant.
This presents issues in versioning, which has consequences in such things as
serialization, blah, blah (I think everyone knows about this particular
problem so I won't repeat it).
The type-safe enumeration design pattern eliminates this problem.
J2SE 1.5.0 (JSR-201) accomplishes "enums" by using a type-safe enumeration
implementation.
i.e. it is just "language candy" to the more long-hand, yet still robust,
implementation.
--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform