Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Permutation and Combination of boolean flags

Tags:

java

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.

like image 268
user1582625 Avatar asked Dec 31 '14 09:12

user1582625


2 Answers

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:
      ...
}
like image 196
M A Avatar answered Oct 12 '22 13:10

M A


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, ..).

like image 27
MajorT Avatar answered Oct 12 '22 14:10

MajorT