有时条件会变得非常复杂,因此为了便于阅读,我通常会将它们拆分并为每个组件指定一个有意义的名称.然而,这会使短路评估失败,这可能造成问题.我想出了一个包装器的方法,但在我看来它太冗长了.
有人可以为此提出一个简洁的解决方案吗?
请参阅下面的代码,了解我的意思:
public class BooleanEvaluator {
// problem: complex boolean expression, hard to read
public static void main1(String[] args) {
if (args != null && args.length == 2 && !args[0].equals(args[1])) {
System.out.println("Args are ok");
}
}
// solution: simplified by splitting up and using meaningful names
// problem: no short circuit evaluation
public static void main2(String[] args) {
boolean argsNotNull = args != null;
boolean argsLengthOk = args.length == 2;
boolean argsAreNotEqual = !args[0].equals(args[1]);
if (argsNotNull && argsLengthOk && …Run Code Online (Sandbox Code Playgroud) private void test() {
// Nested if block
if (true) { // If condition is true
if (true) { // If condition is true
if (true) { // If condition is true
if (true) { // If condition is true
// statement
}
}
}
}
// Above block breaking in below way
// Breaking nested if in multiple with return statement
if (false) { // If condition is false
return;
}
if (false) { // If condition is false …Run Code Online (Sandbox Code Playgroud) 如果我有一个很长的逻辑表达式,将它拆分为许多 if 语句或使用长逻辑表达式是否重要?
例子:
if((A||B)&&(B||C)&&(C||D)&&.....(N||N+1))
System.out.println("Hello World");
Run Code Online (Sandbox Code Playgroud)
或者这更快
if(A||B)
if(B||C)
if(C||D)
...
if(N||N+1)
System.out.println("Hello World");
Run Code Online (Sandbox Code Playgroud)
我认为长表达式更快,但许多 if 可能更好读。但我不确定,许多 if 语句是否可行?
如果检查有多少条件?例如,
if(a==1 && b==1 && c==1 && ... && n==1)
Run Code Online (Sandbox Code Playgroud)
我知道这可能只是通过嵌套ifs来解决,然后它不会是一个多少问题.但坦率地说,我很好奇,似乎无法找到需要多少.
另外,既然我已经引起了你的注意,那么效率之间是否存在差异
if(a==1 && b ==1)
Run Code Online (Sandbox Code Playgroud)
和
if(a==1)
if(b==1)
Run Code Online (Sandbox Code Playgroud) 以下哪项是最有效的选择:
if(myConditionA){
if (myConditionB){
if (myConditionC){
//do something
}
}
}
Run Code Online (Sandbox Code Playgroud)
和
if(myConditionA && myConditionB && myConditionC){
//do something
}
Run Code Online (Sandbox Code Playgroud)
最佳选择是什么,为什么?是否取决于语言?
编辑:这不是关于代码质量的问题。