How to code these conditional statements in more elegant & scalable manner

  • A+

In my software, I need to decide the version of a feature based on 2 parameters. Eg.

Render version 1 -> if (param1 && param2) == true; Render version 2 -> if (!param1 && !param2) == true; Render version 3 -> if only param1 == true; Render version 4 -> if only param2 == true; 

So, to meet this requirement, I wrote a code which looks like this -

if(param1 && param2) //both are true {     version = 1; } else if(!param1 && !param2) //both are false {     version = 2; } else if(!param2) //Means param1 is true {     version = 3; } else { Means param2 is true     version = 4; } 

There are definitely multiple ways to code this but I finalised this approach after trying out different approaches because this is the most readable code I could come up with.
But this piece of code is definitely not scalable because -

  1. Let say tomorrow we want to introduce new param called param3. Then the no. of checks will increase because of multiple possible combinations.
  2. For this software, I am pretty much sure that we will have to accommodate new parameters in future.

Can there be any scalable & readable way to code these requirements.


If you have to enumerate all the possible combinations of Booleans, it's often simplest to convert them into a number:

static final int[] VERSIONS = new int[]{2, 3, 4, 1};  ... version = VERSIONS[(param1 ? 1:0) + (param2 ? 2:0)]; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: