Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to replace or substitute if..else if..else trees in programs?

This question is motivated by something I've lately started to see a bit too often, the if..else if..else structure. While it's simple and has its uses, something about it keeps telling me again and again that it could be substituted with something that's more fine-grained, elegant and just generally easier to keep up-to-date.

To be as specific as possible, this is what I mean:

if (i == 1) {     doOne(); } else if (i == 2) {     doTwo(); } else if (i == 3) {     doThree(); } else {     doNone(); } 

I can think of two simple ways to rewrite that, either by ternary (which is just another way of writing the same structure):

(i == 1) ? doOne() :  (i == 2) ? doTwo() : (i == 3) ? doThree() : doNone(); 

or using Map (in Java and I think in C# too) or Dictionary or any other K/V structure like this:

public interface IFunctor() {     void call(); }  public class OneFunctor implemets IFunctor() {     void call() {         ref.doOne();     } }  /* etc. */      Map<Integer, IFunctor> methods = new HashMap<Integer, IFunctor>(); methods.put(1, new OneFunctor()); methods.put(2, new TwoFunctor()); methods.put(3, new ThreeFunctor()); /* .. */ (methods.get(i) != null) ? methods.get(i).call() : doNone(); 

In fact the Map method above is what I ended up doing last time but now I can't stop thinking that there has to be better alternatives in general for this exact issue.

So, which other -and most likely better- ways to replace the if..else if..else are out there and which one is your favorite?

Your thoughts below this line!


Okay, here are your thoughts:

First, most popular answer was switch statement, like so:

switch (i) {     case 1:  doOne(); break;     case 2:  doTwo(); break;     case 3:  doThree(); break;     default: doNone(); break; } 

That only works for values which can be used in switches, which at least in Java is quite a limiting a factor. Acceptable for simple cases though, naturally.

The other and perhaps a bit fancier way you seem to sugges is to do it using polymorphism. The Youtube lecture linked by CMS is an excellent watch, go see it here: "The Clean Code Talks -- Inheritance, Polymorphism, & Testing" As far as I understood, this would translate to something like this:

public interface Doer {     void do(); }  public class OneDoer implements Doer {     public void do() {         doOne();     } } /* etc. */  /* some method of dependency injection like Factory: */ public class DoerFactory() {     public static Doer getDoer(int i) {         switch (i) {             case 1: return new OneDoer();             case 2: return new TwoDoer();             case 3: return new ThreeDoer();             default: return new NoneDoer();         }     } }  /* in actual code */  Doer operation = DoerFactory.getDoer(i); operation.do(); 

Two interesting points from the Google talk:

  • Use Null Objects instead of returning nulls (and please throw only Runtime Exceptions)
  • Try to write a small project without if:s.

Also in addition one post worth mentioning in my opinion is CDR who provided his perverse habits with us and while not recommended to use, it's just very interesting to look at.

Thank you all for the answers (so far), I think I might have learned something today!

like image 899
Esko Avatar asked Feb 06 '09 07:02

Esko


People also ask

What can be used instead of if-else?

The conditional operator (or Ternary operator) is an alternative for 'if else statement'.

What can I use instead of if-else in JavaScript?

Javascript offers a ternary operator which acts like a one-line if / else statement with a single condition. It works really well for conditionally assigning a value to a variable.

Which of the following is equal to multiple if-else if statement?

Conditional operator can be used for multiple if-else statements..


2 Answers

These constructs can often be replaced by polymorphism. This will give you shorter and less brittle code.

like image 158
Brian Rasmussen Avatar answered Oct 05 '22 04:10

Brian Rasmussen


In Object Oriented languages, it's common to use polymorphism to replace if's.

I liked this Google Clean Code Talk that covers the subject:

The Clean Code Talks -- Inheritance, Polymorphism, & Testing

ABSTRACT

Is your code full of if statements? Switch statements? Do you have the same switch statement in various places? When you make changes do you find yourself making the same change to the same if/switch in several places? Did you ever forget one?

This talk will discuss approaches to using Object Oriented techniques to remove many of those conditionals. The result is cleaner, tighter, better designed code that's easier to test, understand and maintain.

like image 21
Christian C. Salvadó Avatar answered Oct 05 '22 05:10

Christian C. Salvadó