Assignment In Switch
Jake Wharton
jakewharton at gmail.com
Thu Jan 22 00:36:44 UTC 2015
Seeing the newly-added, assignment-free try-with-resources in JDK 9, I was
reminded of a common nuisance regarding the switch statement.
A common pattern is obtaining a value, performing the switch, and acting on
the value in some way. Here's a trivial example:
String protocol = getProtocol();
switch (protocol) {
case "http": return 80;
case "https": return 443;
default: throw new IllegalStateException("Unknown protocol: " + protocol);
}
In this example we only use it in the default case, but you can imagine
other examples which make use of it in the individual cases.
Having parity in the option to use either a value or do an assignment in
creating a switch block would be useful.
switch (String protocol = getProtocol()) {
case "http": return 80;
case "https": return 443;
default: throw new IllegalStateException("Unknown protocol: " + protocol);
}
The extreme simplicity of this example serves only to trivialize the value
of this change. It can be seen as a bit more useful when multiple switches
(linear or nested) are used.
switch (int flag = (value>> 0) & 0xFF) { .. }
switch (int flag = (value>> 8) & 0xFF) { .. }
switch (int flag = (value>>16) & 0xFF) { .. }
switch (int flag = (value>>24) & 0xFF) { .. }
A seemingly minor improvement, but there's a few wins here:
* Parity with the behavior of the try-with-resources block.
* Avoiding the local in the outer scope when it's only use is inside the
switch. As mentioned before, multiple switches that are either written
linearly or nested need to use explicit blocks or add arbitrary variance to
their variable names.
and playing Devil's advocate to myself:
* Relatively low-leverage change. Kills 1LOC in a bunch of places, but no
new magically awesome behavior as try-with-resources brought.
I think this would be a useful (albeit tiny) addition to ease a specific
use case.
More information about the discuss
mailing list