[英]Simplify if statement with multiple conditions
i am stuck to simplify such an if statement.我坚持简化这样的 if 语句。 The if statement in my Project looks somehow like this, but alitle bit more complex.我的项目中的 if 语句看起来有点像这样,但有点复杂。 There i have more if and if else conditions with multiple OR conditions.我有更多带有多个 OR 条件的 if 和 if else 条件。
private int testMethod(int a, char b, String s, float f, double d, TestClass testClass){
if (a == 2 || s.equals("testString") || f == 5 || d == 4 || testClass.getName().equals("testName")){
return 1;
}else if (a == 3 || f == 10 || d == 1){
return 2;
}else {
return 3;
}
}
is there any way to simplify such an if statement?有没有办法简化这样的 if 语句? thanks!谢谢!
If you can simplify this you can try this.如果你可以简化这个,你可以试试这个。 But I think that your code needs in refactoring:)但我认为你的代码需要重构:)
private int testMethod(int a, char b, String s, float f, double d, TestClass testClass){
return isaBoolean(a, s, f, d, testClass) ? 1 : isaBoolean(a, f, d) ? 2 : 3;
}
private boolean isaBoolean(int a, float f, double d) {
return a == 3 || f == 10 || d == 1;
}
private boolean isaBoolean(int a, String s, float f, double d, TestClass testClass) {
return a == 2 || s.equals("testString") || f == 5 || d == 4 || testClass.getName().equals("testName");
}
You can try to check with some boolean logic with the real conditions, but if you have a condition that requires f == 5
or d == 4
there's no quicker way to do it than f == 5 || d == 4
您可以尝试使用一些 boolean 逻辑与实际条件进行检查,但如果您有一个需要f == 5
或d == 4
的条件,那么没有比f == 5 || d == 4
更快的方法了f == 5 || d == 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.