JEP 441: Pattern Matching for switch (suggestion re: handling sealed type selector expressions)
David Alayachew
davidalayachew at gmail.com
Sat Apr 8 23:27:42 UTC 2023
Hello Robert,
I am not a part of the Amber Dev Team, but I have some thoughts.
> If a sealed type S later grows its list of permitted
> subtypes at some point, how should the compiler handle
> switch blocks with S as selector?
>
> In the absence of a catchall label
>
> (i.e. “case default -> ...” or “case S s -> ...”)
>
> the compiler already correctly issues an error that
> coverage is incomplete.
>
> But if the block ended with a catchall label, the
> compiler is silent; the best that can be hoped-for is
> that the coder throws a defensive exception in the
> catchall label (and hope that it is triggered in
> testing).
>
> Suggestion:
>
> Compiler should *disallows* catchall statements in switch
> blocks that use a sealed type in the switch selector
> expression. Note that this special case does not affect
> all the other non-sealed-type selectors (e.g. Object o),
> and appears (to me) to strengthen the safety-value of
> sealed types in this particular scenario (similar to
> enums).
>
> All in Java’s spirit of “least surprise”.
Wow, great catch. This is much trickier than it seems to be at a first
glance.
You want to make sure that a developer doesn't accidentally shoot
themselves in the foot when putting the sealed type itself into the switch
expression when the object being compared against is already a sealed type.
The reason why is that the reader might be fooled into thinking that any
new additions into the sealed type will trigger an exception here, when in
reality, the inclusion of the sealed type itself as a case is basically
synonymous with a default clause BECAUSE THE TYPE OF THE PARAMETER TO THE
SWITCH IS THE SEALED TYPE ITSELF.
Narrow is a good word to use here lol. And I think this suggestion
definitely supports Java's idea of least surprise. I would have fallen for
this for sure.
I agree with you, this should probably throw an error. But it definitely
should at least give a warning.
If your switch expression is longer than a few lines and the permitted
subclasses of the sealed type resemble the sealed type in name, then this
can be a very easy pothole to fall into.
Thank you for pointing this out!
David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230408/2d7cd1c5/attachment-0001.htm>
More information about the amber-dev
mailing list