So I have a class that contains a String-field:
public class A {
private String type = ...
public String getType(){
return this.type;
}
public void setType(String type){
this.type = type;
}
}
I also have a list of all possible types, there are twelve and possibly more in the future.
Now I want to write a method that gets an object of class A and calls a specific method depending on which "type" is in the class.
Is there a smarter solution than writing 12 (or more) if-statements?
Normally I would use the Visitor-pattern but I don't want to create twelve new classes.
edit:
I ended up creating a
Map<String,Function<A,String>> map = new HashMap<String,Function<A,String>>
and then call
A a;
...
map.get(a.getType).apply(a);
If you are using JDK 7 or greater go for a
switch
which accepts String as a parameter and write cases for each.I guess the other answers are correct but, by reading the question I think the more direct answer will be using introspection and convention:
expected output for the example will be:
If convention is not possible you can always create a HashMap with a type to method name mapping.
Instead of storing type as a "free-form" text value, you should be using an
enum
, since you have a well-defined list of values.You can even have the different enums implement the same method differently, by using an abstract method. This will allow you to totally eliminate the error-prone
switch
statements.Below is an example showing both instance values and abstract methods. The pattern shown will keep the implementation out of the enum, while having the compiler catch all uses when a new enum is added.
When you add a new type to the TYPE enum, you also add a new method to the Action interface, which will force you to implement that method in all implementations of the interface. With
switch
statements, you'd get no such safety.