Is there a better (or cleaner) way to write the following code?
if(conditionX) { if(condition1) { // code X1 } else if(condition2) { // code X2 } } else if(conditionY) { if(condition1) { // code Y1 } else if(condition2) { // code Y2 } }
I have a few more conditions, but I guess you get the point.
Remarks. While Excel will allow you to nest up to 64 different IF functions, it's not at all advisable to do so.
Nested IFs are powerful, but they become complicated quickly as you add more levels. One way to avoid more levels is to use IF in combination with the AND and OR functions. These functions return a simple TRUE/FALSE result that works perfectly inside IF, so you can use them to extend the logic of a single IF.
There are four approaches to this problem, none of which is universal:
condition1
and condition2
is tricky, compute them upfront and store them in bool
variablesconditionX
and conditionY
produce a result that lets you unify condition1
and condition2
- This is not always possible, but in some situations you could prepare a variable that unifies the activities taken in the two branches, say, by using a function pointer or a lambda.conditionX
/conditionY
into a place where a subclass is created, and then "reuses" that decision later on by calling a proper override of a virtual function in the interface.switch
- This trick unifies the conditionals, reducing the nesting.Here is an example of the last approach:
int caseNumber = ((conditionX?1:0) << 3) | ((conditionY?1:0) << 2) | ((condition2?1:0) << 1) | ((condition1?1:0) << 0); switch (caseNumber) { case 0x09: case 0x0D: case 0x0F: // code X1 break; case 0x0A: case 0x0E: // code X2 break; case 0x05: case 0x07: // code Y1 break; case 0x06: // code Y2 break; }
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