I'm reluctant to use a switch, but I saw switch will be improved in Java 12
Java 12 added the switch expression as an experimental feature. A Java switch expression is a switch statement which can return a value.
The only use case I found (before Java 12) where switch may be useful is returning different values from a small closed set of cases, e.g.:
switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}
Or in Java 12 example:
return switch(digitInDecimal){ case 0 -> '0'; case 1 -> '1'; case 2 -> '2'; default -> '?';
But I found an old but high-ranked answer that says to avoid multiple return statements:
Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.
So I wonder, is that answer still relevant due to switch changes?
Must I wait for Java 12 where switch can be used without temporary variables and breaks?
Assigning a value to a local variable and then returning that at the end is considered a good practice.
I have no idea when it was considered a good practice. To me, switch
is usually * an indicator that a design error was made. I would rather put my effort into thinking how to avoid a switch than into wondering how to return a value from a switch.
A few examples
Long list of if statements in Java
How to avoid switch-case statements in Java
Converting many 'if else' statements to a cleaner approach
Methods having multiple exits are harder to debug and can be difficult to read.
The same goes for a method that has a lot of break
s - that's what you are going to do if you choose the "local-variable approach".
In my opinion, none of these
// 1
switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}
// 2
String varibleToReturn = null;
switch (input) {
case "A":
varibleToReturn = "1";
break;
case "B":
varibleToReturn = "2";
break;
default:
varibleToReturn = "0";
}
return varibleToReturn;
// 3
return switch(digitInDecimal) {
case 0 -> '0';
case 1 -> '1';
case 2 -> '2';
default -> '?';
}
makes a significant difference, or a slight improvement. Yes, Java-12's switch would give more conciseness and expressiveness, but the fundamental idea remains the same.
Must I wait for Java 12 where switch can be used without temporary variables and breaks?
What does it mean? :) No, the deadline is tomorrow, you have to work with what you've got at hand now.
*I am not underestimating the usefulness of switch. It may come in handy, for instance, when you programme at low-level, or you write an optimization.
I am just saying that in the real world, with Springs, and Hibernates, in a world of patterns, switch is obsolescent.