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

前端 未结 10 2133
隐瞒了意图╮
隐瞒了意图╮ 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 12:46

    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))

提交回复
热议问题