Improve if statement logic

  • A+

I have four bool values:

bool bValue1; bool bValue2; bool bValue3; bool bValue4; 

The acceptable values are:

         Scenario 1 | Scenario 2 | Scenario 3 bValue1: true       | true       | true bValue2: true       | true       | false bValue3: true       | true       | false bValue4: true       | false      | false 

So, for example, this scenario is not acceptable:

bValue1: false bValue2: true bValue3: true bValue4: true 

At the moment I have come up with this if statement to detect bad scenarios:

if(((bValue4 && (!bValue3 || !bValue2 || !bValue1)) ||    ((bValue3 && (!bValue2 || !bValue1)) ||    ((bValue2 && !bValue1) ||    (!bValue1 && !bValue2 && !bValue3 && !bValue4)) {     // There is some error } 

Can that statement logic be improved/simplified?


I would aim for readability: you have just 3 scenario, deal with them with 3 separate ifs

bool valid = false; if (bValue1 && bValue2 && bValue3 && bValue4)     valid = true; //scenario 1 else if (bValue1 && bValue2 && bValue3 &&! bValue4)     valid = true; //scenario 2 else if (bValue1 && !bValue2 && !bValue3 && !bValue4)     valid = true; //scenario 3 

easy to read and debug, IMHO. also, you can assign a variable whichScenario while proceeding with the if

With just 3 scenarios, I would not go with something such "if the first 3 values are true I can avoid check the forth value": it's going to make your code harder to read and maintain

Not an elegant solution maybe, but in this case is ok: easy and readable

If your logic get more complicated, consider using something more to store different available scenarios (as Zladeck is suggesting)


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