Utkarsh Sengar

Software, Growth @upwork, ex-@OpenTable, @ebay, @RedLaserApp, build side projects at thearea42.com, life long learner, always up to something, ๐Ÿš€

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!

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; int opening_time; if (day == WEEKEND) opening_time = 12; else {opening_time = 9;}

Usage of ternary operator in the above example; 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: 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) 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! :)