I have the below piece of code in Java. I need to execute all of the if statements.Is there a better approach to code this.In each of the statement, I would then make a database call.
if (!keyAccntId.equalsIgnoreCase("-1") && !(segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("1");
}
if (!keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("2");
}
if (!keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && (regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("3");
}
if (keyAccntId.equalsIgnoreCase("-1") && !(segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("4");
}
if (keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("5");
}
if (keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && (regionId.equalsIgnoreCase("-1"))) {
templateOrder.add("6");
}
You could create a bitmask and switch on it:
public static final int KEY = 1;
public static final int SEGMENT = 2;
public static final int REGION = 4;
int value = 0;
if (keyAccntId.equalsIgnoreCase("-1")) {
value += KEY;
}
if (segmentId.equalsIgnoreCase("-1")) {
value += SEGMENT;
}
if (regionId.equalsIgnoreCase("-1")) {
value += REGION;
}
That gives you 8 possible values, which you can switch on:
switch(value) {
case 0:
// All false
break;
case KEY:
// only keyAccntId is true
break;
case REGION:
// only segmentId is true
break;
case KEY + REGION:
// segmentId and keyAccntId are true
break;
// So on
}
Added constants to improve readability
A shorter version of @njzk2's answer using Java 7.
public static final int KEY = 0b001, SEGMENT = 0b010, REGION = 0b100;
int comb = (keyAccntId.equals("-1") ? KEY : 0) +
(segmentId.equals("-1") ? SEGMENT : 0) +
(regionId.equals("-1") ? REGION : 0);
switch(comb) {
case 0: /* none are true. */ break;
case REGION: /* only regionId is -1 */ break;
// more combinations.
case KEY + SEGMENT + REGION: /* all are -1 */ break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With