Regarding Java switch statements - using return and omitting breaks in each case(关于 Java switch 语句 - 在每种情况下使用返回和省略中断)
问题描述
鉴于这种方法,这是否代表了一些令人震惊的文体或语义失礼:
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 语句 - 在每种情况下使用返回和省略中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于 Java switch 语句 - 在每种情况下使用返回和省略中断
基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
