Reducing if-else statements in Java
conditional-statements, if-statement, java, refactoring
Solution
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());
}
}
Problem
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?