4

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?

Boann
  • 48,794
  • 16
  • 117
  • 146
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 1
    This answer provides good arguments for multiple return statements: https://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement. I think it's really a matter of style and whether it's making the code more confusing or less. Dogmatic ideals rarely are good in every situation. Using a switch with return statements can be a great way of implementing a factory, for example. – Marc Baumbach Aug 04 '19 at 13:47
  • of course it is relevant - what changed? Nothing - just a **syntax**. There are still multiple exists and debugger will still do the same thing. Some stuff in Java can be easier but it's still Java – m.antkowicz Aug 04 '19 at 13:53
  • @MarcBaumbach I agree, in a closed small set of cases – Ori Marko Aug 04 '19 at 13:53
  • @m.antkowicz java 12 syntax allow you to avoid multiple return statements – Ori Marko Aug 04 '19 at 13:55
  • "removing" *return* word is not "avoiding multiple return statements" ;) just think for a while - how debugger will deal with it? – m.antkowicz Aug 04 '19 at 13:59
  • I don't really understand what you're asking here. You ask what switch is useful for, but also say you're "reluctant" to use it, implying you have a case where it would be useful. – Boann Aug 04 '19 at 14:59
  • @Boann I thought switch was (as Andrew Tobilko stated) *usually an indicator that a design error*, but Java decided to enhance it in version 12, so I asked if the use case I presented of *returning different values from a small closed set of cases* is a valid use case – Ori Marko Aug 04 '19 at 15:01
  • @user7294900 Absolutely its valid. I have never heard this notion that using switch is an error, but it sounds like a myth peddled by cargo-cultists. Two Google developers gave a talk at the JVM language summit last year. They analyzed 300 million lines of Google-maintained Java code, which included 180551 switch statements, and found that 7.1% of all switch statements have all cases assigning to the same variable, and an additional 28.3% of switch statements have all cases simply returning a value. See: https://www.youtube.com/watch?v=sPW2Pz2dI9E – Boann Aug 04 '19 at 15:14

2 Answers2

3

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 breaks - 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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • I understand your point, but if switch is always design error, why java is taking the effort to enhance it? – Ori Marko Aug 04 '19 at 14:06
  • 8
    `switch is always an indicator that a design error was made` - I don't agree. Not always you are creating a huge, flexible libr...ekhm solution. It's always developer's responsibility to **understand** and decide when to use such thing as `switch` and when to implement some *Command* pattern etc – m.antkowicz Aug 04 '19 at 14:07
  • 2
    Why do people dislike the switch statement so much? One it’s best benefits is its ability to create jump tables, the performance of those compared to a lot of ifs is huge, jump tables allow for getting to any given case to occur in O(1) time (except for strings where a single additional string compare has to occur). – vandench Aug 04 '19 at 14:14
  • @user7294900 "several irregularities of the existing switch statement -- **which have long been an irritation to users** -- become impediments. These include the default control flow behavior (fall through) of switch blocks, the default scoping of switch blocks (the block is treated as one single scope) and that switch works only as a statement, even though it is commonly more natural to express multi-way conditionals as expressions." source : https://openjdk.java.net/jeps/325 – Andrew Tobilko Aug 04 '19 at 14:34
  • @user7294900 a language designer doesn't care how you write code, they care how the language allows you to write code (how expressive, laconic, flexible the language is) – Andrew Tobilko Aug 04 '19 at 14:37
0

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?

This is a common misconception, it originates form the phrase: "Single entry, single exit." (Page 24) All this originates from an other era, one that lead to structured programming languages and eventually to object oriented programming languages (like Java).

Don't worry about multiple return statements, there is nothing wrong with it.