[pattern-switch] Opting into totality
forax at univ-mlv.fr
forax at univ-mlv.fr
Tue Sep 1 12:44:35 UTC 2020
----- Mail original -----
> De: "daniel smith" <daniel.smith at oracle.com>
> À: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "Brian Goetz" <brian.goetz at oracle.com>, "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Mardi 1 Septembre 2020 03:56:21
> Objet: Re: [pattern-switch] Opting into totality
>> On Aug 31, 2020, at 5:04 PM, Remi Forax <forax at univ-mlv.fr> wrote:
>> Given that if there is a default it's already a sealed switch and that i can add
>> a default to make it a sealed switch,
>> i struggle to see where to use a classical statement switch and where to use a
>> sealed switch ?
> A competent programmer will definitely need to be able to answer the question
> "should I add 'sealed' to this switch?" I'll take a stab at enumerating all the
> - A switch statement with a 'default' case: doesn't matter. The language already
> supports 'default' in both forms (existing switch statements are non-sealed,
> existing switch expressions are sealed). Pick a favorite style. (Alternatively:
> a switch statement with a 'default' clause is implicitly sealed. Then it's a
> style question of whether or not to be explicit about it.)
> - A switch statement that initializes a local variable or returns at the end of
> a method: doesn't matter. If you don't say 'sealed', flow analysis will catch
> any mistakes. (But there are some gotchas, so maybe 'sealed' (or switch
> expression) is the way to go if you don't want to think about it.)
> - A switch statement that side-effects on just a few of the possible inputs
> ("possible" per static types): must use a non-sealed switch.
> - A switch statement that is optimistically total over an enum/sealed class: use
> a sealed switch to ensure totality checking in the future. Or, if the totality
> is accidental (I cover the cases right now, but don't expect to in the future),
> use a non-sealed switch.
> - A switch statement with a last 'case' intended to be total: use a sealed
> switch to avoid mistakes and (if it's a risk) defend against input type changes
> I think that covers it? There will be some coding style preferences to work out,
> but I think this story will be intuitive to most programmers.
in another thread, i argue that using a keyword at the place of 'default' is perhaps a better syntax,
because if it's not a upfront keyword, so as a developer i will not have to decide which kind of switch to use
until i'm at the end of the switch and at that point i can think in term of totality.
The last three items of your list seems to confirm that idea.
More information about the amber-spec-experts