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