[java] Regarding Java switch statements - using return and omitting breaks in each case

Given this method, does this represent some egregious stylistic or semantic faux pas:

private double translateSlider(int sliderVal) {
    switch (sliderVal) {
        case 0:
            return 1.0;
        case 1:
            return .9;
        case 2:
            return .8;
        case 3:
            return .7;
        case 4:
            return .6;
        default:
            return 1.0;
    }
}  

It's clearly not in line with the Java tutorials here.

However, It's clear, concise and so far has yielded exactly what I need. Is there a compelling, pragmatic reason to create a local variable, assign a value to it within each case, add a break to each case and return the value at the end of the method?

This question is related to java return switch-statement case break

The answer is


I suggest you not use literals.

Other than that the style itself looks fine.


Why not just

private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
    return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}

Or similar?


Best case for human logic to computer generated bytecode would be to utilize code like the following:

private double translateSlider(int sliderVal) {
  float retval = 1.0;

  switch (sliderVal) {
    case 1: retval = 0.9; break;
    case 2: retval = 0.8; break;
    case 3: retval = 0.7; break;
    case 4: retval = 0.6; break;
    case 0:
    default: break;
  }
  return retval;
}

Thus eliminating multiple exits from the method and utilizing the language logically. (ie while sliderVal is an integer range of 1-4 change float value else if sliderVal is 0 and all other values, retval stays the same float value of 1.0)

However something like this with each integer value of sliderVal being (n-(n/10)) one really could just do a lambda and get a faster results:

private double translateSlider = (int sliderVal) -> (1.0-(siderVal/10));

Edit: A modulus of 4 may be in order to keep logic (ie (n-(n/10))%4))


From human intelligence view your code is fine. From static code analysis tools view there are multiple returns, which makes it harder to debug. e.g you cannot set one and only breakpoint immediately before return.

Further you would not hard code the 4 slider steps in an professional app. Either calculate the values by using max - min, etc., or look them up in an array:

public static final double[] SLIDER_VALUES = {1.0, 0.9, 0.8, 0.7, 0.6};
public static final double SLIDER_DEFAULT = 1.0;


private double translateSlider(int sliderValue) {
  double result = SLIDER_DEFAULT;
  if (sliderValue >= 0 && sliderValue < SLIDER_VALUES.length) {
      ret = SLIDER_VALUES[sliderValue];
  }

  return result;
}

I think that what you have written is perfectly fine. I also don't see any readability issue with having multiple return statements.

I would always prefer to return from the point in the code when I know to return and this will avoid running logic below the return.

There can be an argument for having a single return point for debugging and logging. But, in your code, there is no issue of debugging and logging if we use it. It is very simple and readable the way you wrote.


If you're going to have a method that just runs the switch and then returns some value, then sure this way works. But if you want a switch with other stuff in a method then you can't use return or the rest of the code inside the method will not execute. Notice in the tutorial how it has a print after the code? Yours would not be able to do this.


Nope, what you have is fine. You could also do this as a formula (sliderVal < 5 ? (1.0 - 0.1 * sliderVal) : 1.0) or use a Map<Integer,Double>, but what you have is fine.


Yes this is good. Tutorials are not always consize and neat. Not only that, creating local variables is waste of space and inefficient


Though the question is old enough it still can be referenced nowdays.

Semantically that is exactly what Java 12 introduced (https://openjdk.java.net/jeps/325), thus, exactly in that simple example provided I can't see any problem or cons.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript

Examples related to case

PostgreSQL CASE ... END with multiple conditions SQL Server: use CASE with LIKE SQL Server IIF vs CASE SELECT using 'CASE' in SQL SELECT query with CASE condition and SUM() GROUP BY + CASE statement SQL use CASE statement in WHERE IN clause SQL Server - Case Statement where to place CASE WHEN column IS NULL in this query Regarding Java switch statements - using return and omitting breaks in each case

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?