New JEP: Switch Expressions for the Java Language
scolebourne at joda.org
Mon Dec 11 23:53:22 UTC 2017
On 11 December 2017 at 19:59, Brian Goetz <brian.goetz at oracle.com> wrote:
> If you search your heart, you'll realize that the break / fallthrough thing
> is just an emotional "I think this was a mistake and I want an excuse to fix
> it." We didn't drop fallthrough from expression switch because we hate it
> (though we might), but because it simply *doesn't make sense* in an
> expression context. But it does in a statement context -- regardless of how
> much you don't like it.
Fall through is *the* biggest problem with switch and the reason why I
tend to avoid use of the existing switch language feature completely.
The extra break is painful and error prone - fall through shouldn't
even be in the language. I've been burnt by fall through, and I'm sure
many others have too. Some might call it hate, others might call it
The key point the analysis showed was that most of our uses involve
the return keyword in every case, precisely to reduce the risks of the
error-prone use of break. Our code reviews would push developers
towards using switch in that style precisely to reduce fall through
risks. While a switch with return in every case can be converted to an
expression switch, it is my opinion that doing so is not the best
choice. However, that assumes that both expression and statement
switches are equally safe, which is not what is proposed.
What we agree on is that there needs to be both an expression and a
statement form of switch - they both have uses. And we agree that
fall-through does not make sense in an expression switch.
Where we disagree is whether there should be a new statement switch or
not (effectively deprecating the existing one). And we also disagree
on whether fall-through is ever useful, and whether a new statement
switch should mandate a default clause.
In my view, the existing switch statement is something to be avoided
in most situations today, even when it would naturally be the right
language feature, simply because of fall-through. This may come across
as extreme, but developers like myself have learnt the hard way. The
proposed changes don't fix this - I'll still try to avoid the existing
switch statement (because of the risks of fall through), creating this
weird imbalance - statement switch = bad, expression switch = good.
Looking forward, the pattern matching stuff should be built on a
proper foundation, not one hobbled by this mistake from the past -
Java needs a good high quality statement switch just as much as it
needs a good high quality expression switch. One that experienced
developers are willing to use, not forced to avoid. Given that this
would be an easy IDE refactor, I'd much rather see a new statement
switch alongside the new expression switch.
More information about the amber-dev