简化Java IF-ELSE

huangapple go评论83阅读模式
英文:

Simplifying Java IF-ELSE

问题

假设有一个具有 n 个条件的“if语句”:

if (a == b || x == '0' || z == '1' .... || s == 'e') {      // < n 条件 
    result = do_something(); 
}

以下是将其重写的可能方式:

switch (??) {
   case a == b:
   case x == '0':
   case z == '1':
   ...
   case s == 'e':
        result = do_something();
        break;
   default:
        break;
}

这种重写方式会让代码更易读,比起由OR/AND运算符分隔的多个条件来说更加简洁。如果需要添加另一个条件,只需添加另一个case即可。

这种重写是否可行?如果是的话,请提供一种实现方法。
或者
原始的“if语句”本身是否是糟糕编码的结果,因此,是否应该将其视为整个代码需要重新审视和改进的提示?

英文:

Imagine there is an "if statement" with n conditions:

if (a == b || x == &#39;0&#39; || z == &#39;1&#39; .... || s == &#39;e&#39;) {      // &lt; n conditions 
    result = do_something(); 
}

Can this be re-written as below :

switch (??) {
   case a == b:
   case x == &#39;0&#39;:
   case z == &#39;1&#39;;
   ...
   case s == &#39;e&#39;:
        result = do_something();
        break;
   default:
        break;
}

It feels more readable, and less cumbersome than multiple conditions separated by OR/AND operators. If another condition needs to be added then we can just add another case.

Is this possible? If yes, then please share an implementation.
OR
Is the original "if statement" itself a result of bad coding and hence, should be taken as a hint that the entire code needs to be revisited and improved?

答案1

得分: 2

短而直接的回答是不可以,而且你也不应该这样做。
你可以简单地以美观的方式格式化它:

if (a == b 
   || x == '0' 
   || (z == '1' &&  a == 'e')
   || s == 'e') {      
    result = do_something(); 
}

更详细的回答是,你虽然可以这样做,但会变得混乱和不清晰!

在Java(以及大多数其他语言)中,switch 用于在枚举上进行“切换”。因此,你不能使用布尔表达式进行类似 x == b 的切换。甚至简单的情况也不适用,如下所示:

// 这不是真正的Java代码
switch (true) {
    case true:
        System.out.println("true");
        break;
    case false:
        System.out.println("false");
        break;
}

所以唯一剩下的方法是创建一个代表性的枚举... 这对我所能想到的所有情况都是一个糟糕的想法。

如果一个 if 语句真的变得复杂,考虑以下简化的方法:

  • 添加更多注释
  • 使用循环代替
  • 使用更多的 if 语句
  • 使用真值表来简化 if 语句
英文:

The short answer is no you can not and you also should not.
You can simply format it in a nice way:

if (a == b 
   || x == &#39;0&#39; 
   || (z == &#39;1&#39; &amp;&amp;  a == &#39;e&#39;)
   || s == &#39;e&#39;) {      
    result = do_something(); 
}

The long answer is you could but it would be messy and unclear!

In Java (and most other languages) switch is for 'switching' over an enumeration. So you can not switch with boolean expressions like x == b. Not even simple things like this work:

 //NOT REAL JAVA CODE
 switch (true) {
        case true:
            Sytem.out.println(&quot;true&quot;);
            break;
        case false:
            Sytem.out.println(&quot;false&quot;);
            break;
    }

So the only way left would be to create a repsentative enum... Wich is a bad Idea for all cases i can think of.

If an if really escalates consider the following ideas for simplification

  • comment more
  • Use loops instead
  • Use more Ifs instead
  • Use a truth table to simplify the if

答案2

得分: 0

switch语句在我们有一组预定义选项的情况下是一个不错的选择(例如:星期几的天数)。
我们不能在switch语句中比较所有类型的对象和基本类型。我们不能将null值作为参数传递给switch语句。如果这样做,程序将抛出NullPointerException异常。

如果搜索,您会发现更多类似的内容。因此,为了可读性,请不要将if语句更改为switch语句。您可以通过良好的格式化,对if块添加注释,说明条件的使用,并使用嵌套if语句来使if语句更具可读性。

英文:

The switch statement is a good candidate for cases when we have a limited number of options in a pre-defined set (eg: days of the week).
We can't compare all the types of objects and primitives in the switch statement. We can't pass the null value as an argument to a switch statement. If we do it, the program will throw NullPointerException.

You will find more such things if you search. So, just for sake of readability, don't change if statement to switch case. You can make if statement more readable by well formatting, adding comments on if block mentioning the condition use, using nested if.

huangapple
  • 本文由 发表于 2020年8月29日 18:09:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63645785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定