No we should not support enum types derived from strings

deadalnix deadalnix at gmail.com
Mon May 10 21:55:54 UTC 2021


On Monday, 10 May 2021 at 13:30:52 UTC, Paul Backus wrote:
> popFront doesn't return a value, it mutates. So `r` before 
> popFront and `r` after popFront must be the same type, because 
> they are the same variable.
>
> If popFront for a string enum is `r = r[1 .. $]`, and 
> typeof(r[1 .. $]) != typeof(r), then it doesn't work, and 
> string enums can't be ranges (from which it follows that they 
> are not Liskov-substitutable for strings).

r = r[1 .. $] is an error unless r actually is a string. You 
cannot mutate an enum value and have it stay an enum.

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.

The argument that the enum string is not a subtype because it 
breaks he LSP is nonsense, this in fact demonstrate that the type 
system is unsound and it breaks LSP is broken. And this is why 
people end up desperately trying to re-implement it in libraries, 
which result in a ton of more work and complexity for everybody 
involved.


More information about the Digitalmars-d mailing list