Re: Using enums to avoid using switch/if
Giovanni Azua wrote:
In conclusion, even when enum types would be a very strong match for a
design, these limitations would defeat using it.
I had exactly the same problem with a little test program I wrote to
suss out Item 34 of Effective Java, "Emulate extensible enums with
The facts that you cannot derive new classes from existing enum classes,
and the inability to derive from a common abstract base class, are just
too limiting in almost every circumstance. If the enum refers to some
value that could change or need to be extended later, it's better to not
use an enum.
I think you might want to use enums where an API can't only take a range
of values. For example, the Java NIO class ByteBuffer can use either
big endian or little endian buffers. Rather than use values like true
or false or static ints they define their own enumeration ByteOrder with
values BIG_ENDIAN and LITTLE_ENDIAN. This is much clearer than boolean
values and unlike ints it's much more type safe. _ENDIAN is not a user
visible value, and can't change unless the API is changed to support the
new byte order. It's nicely wrapped up internally (even though the
class ByteOrder is public) so there's little change of the user suddenly
needing new values there.
ByteOrder predates enums so ByteOrder is not an enum, but I think it
would be if the API were redone now.