Reputation: 1000
Given the next code samples, What do you think is better, or can you think of another way to code this in a more elegant way?
Duplicated condition in if (two times checking for 'b')
if(a || b) {
doAB();
}
if(b) {
doB();
}
Duplicated code (two times doAB()):
if(a) {
doAB();
}
if(b) {
doAB();
doB();
}
Or a mixed...
if(a || b) {
doAB();
if(b) {
doB();
}
}
EDIT:
A coworker proposed this:
int mask = a?1:b?2:0;
switch(mask) {
case 2:
doB();
case 1:
doAB();
}
Upvotes: 2
Views: 327
Reputation: 140457
A completely different perspective: avoid using if/else stuff.
In OO languages, you can use polymorphism instead of if/else. Instead of asking for some state; to then call a specific method; you simply call a method on some object; and the type of object will make sure that the method does the correct thing.
In other words: at some point, you decide which concrete class has to be instantiated; and later on, you don't worry any more.
You know, the smalltalk language does not even have if (as keyword/language build int).
Of course, you should not go in and just replace your one if with another one. Instead, you could step back and figure if and then how your problem could be re-framed; to make use of polymorphism.
You can turn here for a pretty good video how that can look in reality.
Upvotes: 2
Reputation: 533520
I am guessing the first one is best given the second one is most likely incorrect. I would use the form you consider simple and less error prone.
The second example most like should be
if (a) {
doAB();
} else if (b) {
doAB();
doB();
}
If it is a, it cannot be b and vice versa
In which case you don't need two conditions. It should be a == !b
// a || b is always true
doAB();
if(b) {
doB();
}
Upvotes: 4