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?
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).
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()); } }
Use a Map
(which you'll have to populate) that maps from String
to whatever type your ObjectType.TYPE_x
values are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With