On Monday, 28 May 2012 at 13:47:47 UTC, Andrei Alexandrescu wrote:
On 5/28/12 8:19 AM, foobar wrote:
I have to loudly object to this definition. Given a typical
enumeration
such as:
enum color {Blue, Green, Red};
Who's to say that Blue must equal 0? This is conceptually
plain *wrong*.
A conceptually correct enumeration must NOT expose such
implementation
details as the very poor C/D style enums do.
Depends on what the concept is. The archetype for "enumerating"
is natural numbers, and in that view there's nothing wrong to
attach a natural ordinal to each element of an enumeration.
I do agree that it's wrong to _conflate_ the enumerated value
with it ordinal, so in this program neither comparison should
compile without an explicit cast:
enum E1 { A, B }
enum E2 { C, D }
void main() {
E1 a;
assert(a == 0);
assert(a == E2.C);
}
The first one is probably difficult to disallow at this time,
but the second one almost always indicates a bug, confusion, or
abuse on the user side. We should disallow it.
See functional languages
such as ML for a correct implementation and also Java 5 Enums
(similar
but with an OO flavor).
I've always found it amusing to watch what a kitchen sink Java
enumerations have become. It's as if someone said, "so you
complain Java doesn't have enum? I'll give you enum!" I think
we shouldn't copy that design.
Andrei
It depends on what exactly the general concept is, is this a
predefined set of values or is it an ordered list. I'd argue that
the set is more general and we shouldn't force an ordering when
one isn't strictly required. Of course, the programmer should be
able to add an ordering when it's required.
How to implement an order:
IMO casts usually indicate code smell.
I think something like Color.Red.ordinal states the intention
much better than a cast.
Could you please explain the issues you see in Java's Enum that
cause you to reject such a design?