No we should not support enum types derived from strings

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu May 13 01:16:42 UTC 2021


On 5/12/21 6:00 PM, Paul Backus wrote:
> On Monday, 10 May 2021 at 21:55:54 UTC, deadalnix wrote:
>> If you think that invalidate the LSP, I'm afraid there is a big 
>> misunderstanding about the LSP. Not all operation on a subtype have to 
>> return said subtype. It is made clearer if you consider the slicing 
>> operationa s a member function on an object instead - as I seems 
>> classes and inheritance is the only way OPP is understood these days.
>>
>> class A {
>>    A slice(int start, int end) { ... }
>> }
>>
>> class B : A {}
>>
>> Where is it implied that B's version of the slice operation must 
>> return an A? Nowhere, the LSP absolutely doesn't mandate that. It 
>> mandate that you can pass a B to something that expects an A, and that 
>> thing will behave the way you'd expect.
>>
>> And it does!
>>
>> If your code needs an A, then you mark it as accepting an A as input. 
>> If I have a B and want to pass it to your code, I can too, 
>> transparently. You do not need to even know about the existence of B 
>> when your wrote your code. This is what the LSP is at its core.
>>
>> Back to our string example, the code should accept string (A), with 
>> zero knowledge of the existence of any enum string (B). You should be 
>> able to pass a B to that code and have everything work as expected.
> 
> I concede the points that enum strings do not violate the LSP, and that 
> they are subtypes of string. You're right, and I was wrong.

I was all over run.dlang.org like "Sure that's not going to work... wait 
a second, it does! But that other thing's not going to work... what, 
that works too!" I didn't know D's enums are _that_ odd.

It seems you can do almost everything with an enum that you can do with 
its base type. Keyword being "almost". For example,

x ~= "asd";

works whether x is a string or an enum based on string. However,

x = x ~ "asd";

works if x is a string and does not work if x is an enum derived from 
string. Therefore, a function using that expression works for strings 
but not for enum strings.

Similarly:

x += 3;

works for int and enums derived from int. However,

x = x + 3;

does not. So you can't transparently substitute enums for their base 
type. I suspect there'd be other cases, too.


More information about the Digitalmars-d mailing list