Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing if-else statements in Java

Tags:

I have the following code:

void f(String t) {   if(t.equals("a"))   {     someObject.setType(ObjectType.TYPE_A);   }  else if(t.equals("b"))   {     someObject.setType(ObjectType.TYPE_B);   }  // 50 more similar code  } 

Is there any simple way to rewrite the if-else condition so as not to have that much code?

like image 525
Asha Avatar asked May 02 '12 09:05

Asha


People also ask

How do you stop if-else condition?

Avoid using nested if-else statements. Keep the code linear and straightforward. Utilize creating functions/methods. Compare it when we try to use an if-else statement that is nested and that does not utilize the power of the return statement, We get this (Code 1.4).


2 Answers

You should use something to eliminate the repetition of someObject.setType(ObjectType....)) If ObjectType is an enum, then write a method there similar to valueOf that will achieve that. See if you like this kind of solution:

void f(String t) { someObject.setType(ObjectType.byName(t)); }  enum ObjectType {   TYPE_A, TYPE_B;   public static ObjectType byName(String name) {     return valueOf("TYPE_" + name.toUpperCase());   } } 
like image 82
Marko Topolnik Avatar answered Oct 03 '22 11:10

Marko Topolnik


Use a Map (which you'll have to populate) that maps from String to whatever type your ObjectType.TYPE_x values are.

like image 41
Alnitak Avatar answered Oct 03 '22 11:10

Alnitak