如何制作if else语句功能
boolean condition1;
boolean condition2;
final Object a = new Object();
final Object b = new Object();
final Object c = new Object();
final Object d = new Object();
if (condition1 && condition2) {
return a;
}
else if (condition1 && !condition2) {
return b;
}
else if (!condition1 && condition2) {
return c;
}
else {
return d;
}
我想知道如何重构这种类型的条件语句以使其更具功能性,而不会优先考虑性能上的开销。
我在考虑将谓词映射到对象,这是一种方法吗?
答案 0 :(得分:2)
我添加了两个条件来增加它的味道。 if / else语句可以非常深入,因此您可以使用逐位来澄清事物并合并条件。对我而言,这澄清了代码 - 无论有多少条件,都会导致代码深入一层。
final int BIT_CONDITION_1 = 0x01;
final int BIT_CONDITION_2 = 0x02;
final int BIT_CONDITION_3 = 0x04;
final int BIT_CONDITION_4 = 0x08;
boolean condition1 = false;
boolean condition2 = false;
boolean condition3 = false;
boolean condition4 = false;
int mergedConditions = 0;
if (condition1)
mergedConditions |= BIT_CONDITION_1;
if (condition2)
mergedConditions |= BIT_CONDITION_2;
if (condition3)
mergedConditions |= BIT_CONDITION_3;
if (condition4)
mergedConditions |= BIT_CONDITION_4;
// continue as needed
// now you can check all conditions using the set bits.
switch(mergedConditions) {
case 0: // no bits set
System.out.println("No bits set");
break;
case 1:
System.out.println("Conditions set = 1");
break;
case 2:
System.out.println("Conditions set = 2");
break;
// You can also clarify case statements by using constants
case (BIT_CONDITION_1 | BIT_CONDITION_2):
System.out.println("Conditions set = 1,2");
break;
case 4:
System.out.println("Conditions set = 3");
break;
case 5:
System.out.println("Conditions set = 1,3");
break;
case 6:
System.out.println("Conditions set = 2,3");
break;
case 7:
System.out.println("Conditions set = 1,2,3");
break;
case 8:
System.out.println("Conditions set = 4");
break;
case 9:
System.out.println("Conditions set = 1,4");
break;
case 10:
System.out.println("Conditions set = 2,4");
break;
case 11:
System.out.println("Conditions set = 1,2,4");
break;
// etc ... Continue as needed
}
答案 1 :(得分:1)
对于两个条件,if / then / else语句没有任何问题。如果您有更多条件,可以使用真值表“简化”代码。
$posts = Post::all()->toArray();
current($posts);
next($posts);
不确定这是否是您的想法,但这是分派多个条件的典型方式。乍一看它看起来很神秘,如果你记录所有条件的整个真值表,它可能非常安全,因为它迫使你考虑所有可能的组合。当你有两个以上的条件时,这真的有用。