3 Best Possible If-Else Construct Alternatives
Share on Facebook
My current JAVA project requires a lot of check points, for example, 1. if the format of the ID passed is correct, then go ahead and 2. check if ID exists or not, if it does, 3. then check if ID has some kind of specific attributes or not and so on!
So, I was using the regular if-else for something like 6-7times!
if([condition]) { [do this] }else if([condition]){ [do this]}else if{[do this] }else if([condition]){ }else{ [do this]}
When I looked back at the code, it sucked! The deep nesting of the if-else construct made the code hard to understand and comprehend!

So, I searched a little for some logical if-else construct alternatives and I came up with these three useful techniques;
- Ternary operator (?:) and
- Logic Grid
- Switch Statement (It is also a good alternative which makes the code look good. Its also pretty easy, so I won’t cover it here.)
Lets take a look at the 1st and a simpler process using ternary operator:
1. If-Else Construct Usage;
if (day == WEEKEND)
opening_time = 12;
else {opening_time = 9;}
Usage of ternary operator in the above example;
[condition ? value if true : value if false]
Ok, so that was easy! Now lets take a look at LogicGrid technique which is very impressive and and an elegant way!
2. If-Else Construct:
if (b) {
result = 1;
} else {
result = 2;
}
} else if (c) {
if (b) {
result = 3;
} else {
result = 4;
}
} else if (!c) {
result = 5;
}
Using Logic Grid: (C++ code here changed to Java)
{
int index = 0;
int[] results = { 5,4,5,3,2,2,1,1 };
if(a) index = index | 4;
if(b) index = index | 2;
if(c) index = index | 1;
return results[index];
}
The logic grid method is amazing!! Once you get hold of it, you will always use it, the code is much more organized and understandable now!
Hope it helps! ![]()
Related Posts:
- Get the new Google Homepage!
- JMS application on Ubuntu 9.10 using Eclipse Ganymede
- Install Google Chrome OS on Virtual Box
- Sync iPod on Ubuntu 9.10 using Virtual Box 3.0.10
- Amazing Video Wall by Blinkx.com
Utkarsh Sengar 8:45 pm on December 11, 2009 Permalink
3 Best Possible If-Else Construct Alternatives | the lost logbook http://bit.ly/70Ty2C
Jake 10:25 pm on January 4, 2010 Permalink
Amazing! Nice tip. All compiled at one place.
3 Best Possible If-Else Construct Alternatives | MarketingTypo.com 3:50 pm on April 1, 2010 Permalink
[...] View full post on the lost logbook [...]