Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove large if-else-if chain [duplicate]

Tags:

Possible Duplicate:
Long list of if statements in Java

I was tasked to work with some code, and there is a giant if-else-if chain (100+ else-ifs) that checks Strings.

What are some good techniques to update this code as to where the if-else-if chain can be shrunken down to something much more manageable.

The chain looks something like this:

if(name.equals("abc")){     do something } else if(name.equals("xyz")){     do something different } else if(name.equals("mno")){     do something different } ...... ..... else{     error } 
like image 212
user906153 Avatar asked Sep 08 '11 14:09

user906153


People also ask

What can I use instead of if-else?

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


Video Answer


2 Answers

You can extract the code in each branch to a separate method, then turn the methods into implementations of a common base interface (let's call it Handler). After that, you can fill a Map<String, Handler> and just look up and execute the right handler for given string.

Unfortunately the implementation of 100+ subclasses for the interface requires quite a lot of boilerplate code, but currently there is no simpler way in Java to achieve this. Implementing the cases as elements of an Enum may help somewhat - here is an example. The ideal solution would be using closures / lambdas, but alas we have to wait till Java 8 for that...

like image 115
Péter Török Avatar answered Jan 04 '23 02:01

Péter Török


Some options / ideas:

  • Leave it as it is - it's not fundamentally broken, and is reasonably clear and simple to maintain
  • Use a switch statement (if you are using Java 7) - not sure if this gains you much though
  • Create a HashMap of String to FunctionObjects where the function objects implement the required behaviour as a method. Then your calling code is just: hashMap.get(name).doSomething();
  • Break it into a heirarchy of function calls by sub-grouping the strings. You could do this by taking each letter in turn, so one branch handles all the names starting with 'a' etc.
  • Refactor so that you don't pass the name as a String but instead pass a named object. Then you can just do namedObject.doSomething()
like image 27
mikera Avatar answered Jan 04 '23 00:01

mikera