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?
You can also think of the -> as a return statement which returns a value from the switch expression, and thus breaks the execution of the switch expression. The Java switch expression also works with Java String values.
Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached. This continuation may be desirable in some situations. The default statement is executed if no case constant-expression value is equal to the value of expression .
Yes, you can use return instead of break ... break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.
When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break.
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.
That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.
While we are on the topic you must check this out. Its an interesting read.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With