the lost logbook

Utkarsh's mind.random() on Programming, India and Startups

3 Best Possible If-Else Construct Alternatives

3 comments

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!

1
2
3
4
5
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!

Comic Via

So, I searched a little for some logical if-else construct alternatives and I came up with these three useful techniques;





  1. Ternary operator (?:) and
  2. Logic Grid
  3. 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;

1
2
3
4
 int opening_time;
if (day == WEEKEND)
opening_time = 12;
else {opening_time = 9;}

Usage of ternary operator in the above example;

1
int opening_time = (day == WEEKEND) ? 12 : 9;

[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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (a) {
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)

1
2
3
4
5
6
7
8
9
int getResult (boolean a, boolean b,boolean c)
{
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! :)

Written by Utkarsh

December 12th, 2009 at 2:12 am

Posted in Technology

3 Responses to '3 Best Possible If-Else Construct Alternatives'

Subscribe to comments with RSS or TrackBack to '3 Best Possible If-Else Construct Alternatives'.

  1. 3 Best Possible If-Else Construct Alternatives | the lost logbook http://bit.ly/70Ty2C

    Utkarsh Sengar

    11 Dec 09 at 8:45 pm

  2. Amazing! Nice tip. All compiled at one place.

    Jake

    4 Jan 10 at 10:25 pm

  3. […] View full post on the lost logbook […]

Leave a Reply

*

Page optimized by WP Minify WordPress Plugin