Reputation: 2146
Appologies for the abstract nature of the question, but although I'm thinking of the implementation in something like java or c#, it is the concept in general that is slightly bugging me at the moment.
With most languages when one uses boolean logic for testing purposes only one answer will be valid.
if (fridgeDoorClosed !=true)
closeFridge();
else
eatSandwich();
But what about when multiple paths may be correct? Supposing a form on a webpage where the user uses checkboxes to choose what s/he wants to see. A horrendously inelegant way to do this would be:
if ((checkbox1==true)&&(checkbox2==true)&&(checkbox3==true))
blah
else if
((checkbox1==true)&&(checkbox2==true)&&(checkbox3==false))
blah
and so on, being careful about order, of course.
In languages such as java and c# case switch statements can be used, leaving out the usual break statements to force a cascade. But can such a method be used in a practical manner?
Upvotes: 0
Views: 465
Reputation: 3121
There already in forum is something similar -> get-rid-of-ugly-if-statements
If you known Polish, you can watch presentation, about 'get-fid-of-if' youtube film from confitura (interesting part is from 25.20)
If you don't known Polish, Author say that: a) the most important is readability (unworking, but readable code is better, than working and unreadable) b) what code (one of 3) was the best? It depends, on many conditions (for example, if you working with college students the best is simple, if you write code for graphics engine use the 'math').
p.s. in c# if statement, you don't neet to write '=true'
if ((checkbox1)&&(checkbox2)&&(checkbox3)
blah
Upvotes: 1
Reputation: 324630
Generally I would do something like this:
if( checkbox1) {
if( checkbox2) {
if( checkbox3) {
// all three
}
else {
// a, b, not c
}
}
// .......
}
But depending on the situation you could do this:
boxes = (checkbox1?1:0)+(checkbox2?2:0)+(checkbox3?4:0);
switch(boxes) {
case 0: // no boxes
break;
case 1: // box 1, not 2 or 3
break;
case 2: // box 2, not 1 or 3
break;
// ........
}
Upvotes: 1