gpt4 book ai didi

Java 开关用例

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:35 24 4
gpt4 key购买 nike

我不愿意使用开关,但我看到了switch will be improved in Java 12

Java 12 added the switch expression as an experimental feature. A Java switch expression is a switch statement which can return a value.

我发现(在 Java 12 之前)switch 可能有用的唯一用例是从一小组封闭的案例中返回不同的值,例如:

    switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}

或者在 Java 12 示例中:

return
switch(digitInDecimal){
case 0 -> '0';
case 1 -> '1';
case 2 -> '2';
default -> '?';

但是我发现了一个老的但是排名靠前的answer那说要避免多个返回语句:

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.

所以我想知道,由于 switch 更改,这个答案是否仍然相关?

我必须等待 Java 12 才能在没有临时变量和中断的情况下使用 switch 吗?

最佳答案

Assigning a value to a local variable and then returning that at the end is considered a good practice.

我不知道什么时候它被认为是一种好的做法。对我来说,switch 通常 * 是设计错误的指示器。我宁愿把精力放在思考如何避免 switch 上,也不愿考虑如何从 switch 返回值。

几个例子

Long list of if statements in Java
How to avoid switch-case statements in Java
Converting many 'if else' statements to a cleaner approach

Methods having multiple exits are harder to debug and can be difficult to read.

对于有很多 break 的方法也是如此 - 如果您选择“局部变量方法”,这就是您要做的。

在我看来,这些都不是

// 1
switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}

// 2
String varibleToReturn = null;
switch (input) {
case "A":
varibleToReturn = "1";
break;
case "B":
varibleToReturn = "2";
break;
default:
varibleToReturn = "0";
}
return varibleToReturn;

// 3
return switch(digitInDecimal) {
case 0 -> '0';
case 1 -> '1';
case 2 -> '2';
default -> '?';
}

产生显着差异,或略有改善。是的,Java-12 的 switch 会提供更多的简洁性和表现力,但基本思想保持不变。

Must I wait for Java 12 where switch can be used without temporary variables and breaks?

这是什么意思? :) 不,截止日期是明天,您必须使用手头的东西。


*我并没有低估 switch 的用处。它可能会派上用场,例如,当您在低级别编程或编写优化时。

我只是说在现实世界中,有了 SpringsHibernates,在模式世界中,switch 已经过时了。

关于Java 开关用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57347001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com