Enum literals, good? bad? what do you think?
russhy
russhy at gmail.com
Tue Jul 20 16:55:14 UTC 2021
On Tuesday, 20 July 2021 at 16:12:05 UTC, H. S. Teoh wrote:
> On Tue, Jul 20, 2021 at 03:50:49PM +0000, russhy via
> Digitalmars-d wrote:
>> Hello
>>
>> I all the time wondered why we always have to be so much
>> verbose with enum, when it's not casting to primitives, it is
>> about repeating their long type name, constantly, all the time
> [...]
>
> OT1H, having to qualify enums by their full name is good, it
> helps to avoid the mess in C where libraries sometimes define
> conflicting values under the same name, e.g.,
>
> // somelib.h
> #define ERROR 0
> #define OK 1
>
> // someotherlib.h
> #define ERROR -1
> #define OK 0
>
> In D, if you used an enum, you'd have to quality which ERROR or
> OK you're referring to, which avoids conflicts and also avoids
> unexpected symbol hijacking. E.g., somelib.h used to define
> MY_OK = 1, but after upgrading they renamed MY_OK to OK, now
> your code that referred to OK in someotherlib.h may
> accidentally get the wrong value.
>
> OTOH, I agree that sometimes D enums become rather verbose.
> Especially in switch statements where you have to repeat their
> name for every case. Fortunately, this is where D's `with`
> statement comes in helpful:
>
> enum MyEnum { blah, bleh, bluh }
> MyEnum val = ...;
> final switch (val) {
> case MyEnum.blah: ...
> case MyEnum.bleh: ...
> case MyEnum.bluh: ...
> }
>
> can be replaced with:
>
> enum MyEnum { blah, bleh, bluh }
> MyEnum val = ...;
> final switch (val) with (MyEnum) {
> case blah: ... // look ma! less repetition!
> case bleh: ...
> case bluh: ...
> }
>
>
> T
That's a good point, and that ``switch with`` is very nice and
solve the issue
I didn't know about ``with`` until adam mentioned it, could the
rule in ``switch`` be relaxed and implement something akin to
``with`` ?
More information about the Digitalmars-d
mailing list