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

前端 未结 10 2116
隐瞒了意图╮
隐瞒了意图╮ 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: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;
    }
    

提交回复
热议问题