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

前端 未结 10 2111
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 12:29

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

private double translateSlider(int sliderVal) {
    switch (sliderVal) {
           


        
相关标签:
10条回答
  • 2021-02-01 13:01

    I suggest you not use literals.

    Other than that the style itself looks fine.

    0 讨论(0)
  • 2021-02-01 13:02

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 13:03

    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.

    0 讨论(0)
  • 2021-02-01 13:09

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

    0 讨论(0)
提交回复
热议问题