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

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jul 20 16:12:05 UTC 2021

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: ...


Questions are the beginning of intelligence, but the fear of God is the beginning of wisdom.

More information about the Digitalmars-d mailing list