[patterns] reconsidering how the created variable name binds

Brian Goetz brian.goetz at oracle.com
Tue Dec 31 15:29:02 UTC 2019


> << refactoring robustness is a core part of the design >>

Of course, _which_ refactorings are important is a subjective matter, 
and its easy to forget one.  And, sometimes we are hampered by existing 
language choices.  For example, its possible to refactor an if-elsif 
chain of instanceof tests against the same target to a pattern switch, 
but not necessarily vice-versa -- because of fallthrough.  (It is 
possible, but it involves hoisting out a bunch of ugly booleans that 
pollute the control flow.)  Similarly, the fact that instanceof handles 
null more gracefully than switch also poses an impediment to some 
refactorings.

> Should I be able to refactor this:
>      if (!(z instanceof Integer i)) throw new IllegalStateException();
>      //use i here
>
> to this:
>
>     switch (z) {
>          case Integer i: break;
>          default: throw new IllegalStateException();
>      }
>
>      // use i here
>
> That obviously won't work, as switch introduces mandatory scope.

No.  The key is: the `i` in the second example is enclosed by the 
mandatory switch scope, as you surmise.  Going in the other direction, 
though, you could get the same effect as the switch by introducing an 
explicit scope, refactoring to:

     { if (!(z instanceof Integer i)) throw new IllegalStateException(); }
     // can't use i here


> Normally in refactor scripts, the refactor script will occasionally
> 'escape' the local variable declaration in order to make scoping rules
> work, i.e. some construct of the form of `int i = 10;` is broken apart by
> the refactor into `int i;`, showing up above some introduced scope, and `i
> = 10;` showing up inside it. I don't think that's possible with the pattern
> match construct.
>
> I guess that means it's just 'robust under refactorings that do not
> introduce new scopes', but presumably most refactorings fit that particular
> description, and catering to the few refactorings that do isn't worthwhile.

Yep, there are limits imposed by quirks of the existing constructs 
(null, fallthrough, scoping.)  We try to do as well as we can.



More information about the amber-dev mailing list