Enum literals, good? bad? what do you think?

Patrick Schluter Patrick.Schluter at bbox.fr
Thu Jul 22 07:33:34 UTC 2021


On Thursday, 22 July 2021 at 04:37:43 UTC, Walter Bright wrote:
> On 7/21/2021 8:47 PM, Mathias LANG wrote:
>> What I meant was that instead of recommending our users to use 
>> `switch (value) with `(EnumType)`, we could just make it the 
>> default since it's the common case with enums. Unless we think 
>> that requiring the type of the enum be spelt out is better.
>> 
>> It could add to the long list of those usability enhancements 
>> that are a hallmark of D (like `_` in number literals). I 
>> personally don't mind the verbosity, but I heard this 
>> complaint a few times over the years.
>
> Ok, I see what you mean. If it was restricted to the case value 
> expressions, there is merit to the idea. But suppose:
>
>     enum A = 3, B = 4;
>     switch (x) {
>       case A: ...
>       case B: ...
>     }
>
> there isn't much of a clue that `case A` is not `case 3`, which 
> matters more and more the larger the program gets.

This case is comparable to variable shadowing and should then be 
handled the same way.
btw, as of now, what will happen in the case

```
enum ENUM { A, B, C }
     ENUM x = ENUM.A;
     enum A = 3, B = 4;

     switch (x) with (ENUM) {
        case A: writeln("case A=", cast(int)A);break;
        case B: writeln("case B=", cast(int)B);break;
        default:writeln("whatever x=", cast(int)x);
     }
```
https://run.dlang.io/is/7Ar7dQ

it will use the values defined in ENUM and ignore the `enum A` 
and `enum B` values.
The compiler should at least warn of the ambiguity if the 
`with(ENUM)` is removed.


> One thing I've learned with D is that programmers often have 
> mental models of how symbol lookup is done that diverge 
> substantially from how it actually works, and I've never been 
> able to communicate how things actually work to them. Putting a 
> special case in like this is pretty risky.




More information about the Digitalmars-d mailing list