Enumerating True And False

Some guy asserted in EnumeratedTypesInJava that an enumeration needs to have a totally ordered test operator and a successor mapping. Yet the boolean type (Java's one enumeration) does not provide either of those. It really makes no sense to decide whether "true" is less than or greater than "false", and the type seems pretty useful without this capability.

In any event, what brought me to the Wiki today was another thought I had regarding enumerated types in Java. In Smalltalk-80, true and false are actually represented by elements of separate classes called True and False. True and False inherit from an abstract class Boolean.

The cool thing about this approach is that it makes operations on Booleans really easy to write. For example, the code for the "or" operator is simply to return true in class True, and return the next argument in class False.

Now, does this make sense in Java and/or with different classes? In the month example, I think it does. Each month is its own singleton class, a subclass of Month. Months can still be compared using ==, or, if you are worried about serialization, you can write Month.equals() as "return (this instanceOf (m.class)". Enumerations are still the same.

Thoughts, opinions, contrary statements?

-- BillTrost

A neat implementation would be to represent each month as an anonymous inner class of the Month class, each of which is derived from Month.

OTOH, it would increase the number of classes and so increase loading time, which might be important for networked applications.

--NatPryce

My assertion stems from seeing several pieces of code other rather from any profound analysis perspective.

If you are writing code that must perform some test for all possible values of the enumeration, you need an operator which returns the "next" value in the sequence. A total ordering allows you to test whether you have already processed a value.

Are the booleans really an enumerated type? Do you consider float to be an enumerated type? Does a successor on float make intuitive sense? I don't consider any of the non-object types in Java to be enumerated types - Sun decided not to support enumerated types.

The fact that some non-object types, e.g. int can be used to implement enumerated types is another matter. -- A guy


Those are fair questions. I guess if I were forced to take a stand I would classify an enumeration as a finite type containing constant elements. Admittedly, int is technically an enumeration because it is, in fact, finite, but it's not "supposed" to be. The simplest fix to my definition would be to simply exclude numeric types.

-- BillTrost

EditText of this page (last edited April 10, 2012) or FindPage with title or text search