Regarding Java switch statements - using return an

2020-05-19 03:57发布

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?

9条回答
迷人小祖宗
2楼-- · 2020-05-19 04:28

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.

查看更多
别忘想泡老子
3楼-- · 2020-05-19 04:28

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.

查看更多
小情绪 Triste *
4楼-- · 2020-05-19 04:32

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

查看更多
登录 后发表回答