6

I have some boolean variables which will be passed as arguments

boolean var1;
boolean var2;
boolean var3;
boolean var4;

Depending on these variables, I have to code something like this

if (var1 && !var2 && !var3 && !var4) {
  //do something
}
elsif (var1 && var2 && !var3 && !var4) {
  //do something
}

. . . and so on.. using all the possible combinations. I can do this using if-else statement. Need to know is there some better approach. Thanks in advance.

user1582625
  • 303
  • 1
  • 2
  • 7

4 Answers4

5

Build a bit pattern out of the four boolean arguments, e.g. 0110 means var1 = false, var2 = true, var3 = true and var4 = false.

Then you can use the switch construct on the generated numbers.

int b = (var1 ? 8 : 0) | (var2 ? 4 : 0) | (var3 ? 2 : 0) | (var4 ? 1 : 0);
switch(b) {
   case 0:
      ...
   case 1:
      ...
}
M A
  • 71,713
  • 13
  • 134
  • 174
1

I don't think there is a better approach. It depends on your code paths. If you really need 2*2*2*2 code paths, you will need to write that code somewhere. Either you make a big if-else block like you suggest, or you find another way to point to an implementation based on your flags (strategy pattern, switch, ..).

MajorT
  • 221
  • 1
  • 12
0

The algorithm has 2 steps:

Step 1. Create N! permutation cases,

Step 2. In specific case, using De Morgan theorem:

VAR_1 && !VAR_2 && !VAR_3 && ... && !VAR_N  =  VAR_1 AND !OR(VAR_2, VAR_3, ... VAR_N)

similar, we have other case:

AND(VAR_1, VAR_2) AND !OR(VAR_3, VAR_4, ..., VAR_N)
AND(VAR_1, VAR_2, VAR_3) AND !OR(VAR_4, VAR5, ..., VAR_N)
...
AND(VAR_1, ..., VAR_(N-1)) AND !OR(VAR_N)
Vy Do
  • 46,709
  • 59
  • 215
  • 313
0

You cannot reduce number of conditions but can simplify the conditions like this using Arrays.equals:

boolean var1;
boolean var2;
boolean var3;
boolean var4;

boolean[] varArr = new boolean[]{var1,  var2, var3, var4};

if (Arrays.equals(varArr, new boolean[]{false, false, false, false})) {
    // handle case1
} else if (Arrays.equals(varArr, new boolean[]{true, false, false, false})) {
    // handle case2
} else if (Arrays.equals(varArr, new boolean[]{true, true, false, false})) {
    // handle case3
}
...
...
anubhava
  • 761,203
  • 64
  • 569
  • 643