enum

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 11 18:59:51 PDT 2014


On Friday, April 11, 2014 17:01:15 Andrei Alexandrescu wrote:
> On 4/11/14, 12:31 PM, Jonathan M Davis wrote:
> > On Friday, April 11, 2014 08:22:01 Steven Schveighoffer wrote:
> >> final enum name { ... }
> > 
> > This only makes sense to me if it's then illegal to declare any variables
> > of that enum type, because if you're looking to use an enum to give a
> > list of possible values rather than enumerating the exact list of values,
> > why would you be marking _any_ variable as being of that enum type?
> 
> I don't understand that contention. "final" clarifies that the set of
> values in the enumeration is closed.

I take issue with the idea that it makes sense to have any variables of an 
enum type that isn't one of the values enumerated in the enum. If you want to 
only enumerate a portion of the possible values, then that would mean that 
you're declaring a set of related constants rather than the set of possible 
values for a new type. They're just names for values of an existing type which 
can have other values, and as such, it makes no sense for those constants to 
introduce a new type. They're just constants put in a separate namespace, not 
an enumeration.

So, basically, I'm arguing that it makes no sense to ever have an enum 
variable of an enum type that is not intended to enumerate _all_ of its 
possible values. So, if you want to use an enum to group constants together, 
that's fine, but if that's the purpose, then it shouldn't be creating a new 
type. It should just be scoping the constants so that they're grouped together 
for access (e.g. Color.red and Color.green instead of the unscoped constants 
red and green). And that's trivial enough to do with a struct with manifest 
constants in it (though it's a bit more verbose). You don't need an enum for 
that.

As such, I think that if we have enum and final enum, then enum shouldn't 
actually create a new type - just a namespace for a group of constants.

Or we could just say that all enum types enumerate all of their possible 
values and put the full restrictions in the compiler against setting them or 
mutating them to any other values, and then if someone uses an enum to list 
constants rather than intending it to be a true enumeration, then they're fine 
just so long as they don't try to declare a variable of the enum type, since 
the enum values will implicitly convert to the base type. So, all of the 
restrictions on the enum type which are intended to protect it from having 
other values wouldn't cause any problems for those trying to use the enum to 
put constants in a common namespace. It would only cause problems if you tried 
to use a variable of the enum type and give it other values, which I don't 
think is a problem at all, since they weren't intended to introduce a new type 
in the first place.

- Jonathan M Davis


More information about the Digitalmars-d mailing list