How to improve logic to check whether 4 boolean values match some cases

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 surely, but in this case is ok: easy and readable.

If your logic gets more complicated, throw away that code and consider using something more to store different available scenarios (as Zladeck is suggesting).

I really love the first suggestion given in this answer: easy to read, not error prone, maintainable

(Almost) off topic:

I don’t write lot of answers here at StackOverflow. It’s really funny that the above accepted answer is by far the most appreciated answer in my history (never had more than 5-10 upvotes before I think) while actually is not what I usually think is the “right” way to do it.

But simplicity is often “the right way to do it”, many people seems to think this and I should think it more than I do 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)