关于Java switch语句-在每种情况下都使用return和省略符 [英] Regarding Java switch statements - using return and omitting breaks in each case

查看:823
本文介绍了关于Java switch语句-在每种情况下都使用return和省略符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于这种方法,这是否代表了一些过分的风格或语义上的伪造:

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;
    }
}  

这显然不符合Java教程此处.

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?

推荐答案

将值分配给局部变量,然后最后返回该值被认为是一种好习惯.具有多个出口的方法很难调试,并且可以很难阅读.

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.

这篇关于关于Java switch语句-在每种情况下都使用return和省略符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆