samedi 16 février 2019

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

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.

Aucun commentaire:

Enregistrer un commentaire