Notes on Java 8

Enum types are constructs which represent sets of known values. They are useful, but are something of a kludge in a way that reminds me of the String class shenanigans.

Enums types are declared like other composite types, like class or interface. They have their own keyword. Unsurprisingly, it is enum.

Now the use for them is clear: it avoids the need of having a load of “public static final” fields laying around, and gives them common functionality, like a “static T[] values()” which returns all the possible values, or a static “T valueOf(String)” which returns the value with a name matching the String parameter.

They can be used to build finite state machines, and can be used with the “switch” construct. They help avoid silly-in-hindsight but maybe-really-serious bugs by catching typos: all values must be declared, if a match was made with a String literal a typo would create a branch of never-used-code.

Another neat feat is that they can return their name as a String, and can be compared to each other – the order in which they’re declared determines which value is “first” and which is “last”.

Now, enums are actually classes with shenanigans added. Even though it’s never specified, an enum type is a class which extends from java.lang.Enum<E> and has some methods (which I suspect are injected at compile time, it would be nice to confirm by looking inside a .class file; for the record, clever use of reflections would make creating a generic method which is invoked for the special, shared functionality rather trivial)

As it’s a class, you can write other methods and declare variables in it.

But you can’t build an enum by hand – extending java.lang.Enum<E> is illegal. Even though it’s not final. Which is an annoying inconsistency and lack of elegance. Was it necessary to implement like this? It’s very likely, as there are many really smart people working on the Java language. It’s not pleasant, though.

Enums are treated like special citizens, and even have particular data structures and algorithms tuned to them (EnumSet and EnumMap); which further reminds me of the shenanigans that go on with the String class, what with special in-memory representation and all.

This are not bad things in and of themselves – the way that Enums and Strings break out of the pattern of the language; they don’t fit with the mental model that would arise out of studying the rest of the architecture, though, so care needs to be taken, that they won’t come back to bite you.

Leave a Reply

Your email address will not be published. Required fields are marked *