I know there are already some questions about replacing if else with polymorphism, for example:
Applying Replace Conditional with Composition in functional programming
Is it wrong to use any type of parameter to determine behavior?
Should conditional logic be always coded via type system where possible?
which the following is bad:
public static void main(String[] args) {
test("Cat");
}
public static void test(String str){
if(str.equals("Cat")){
System.out.println("cat");
}else if(str.equals("Dog")){
System.out.println("dog");
}
}
And should wrap the "what to do" into a class and let "polymorphism" decides what should the class do:
public interface Animal{
public void print();
}
public class Cat implements Animal{
public void print(){
System.out.println("cat");
}
}
public class Dog implements Animal{
public void print(){
System.out.println("dog");
}
}
public static void main(String[] args) {
Animal animal=new Cat();
animal.print();
}
However, I found most of the questions above is not practical for me: either the "what to do" is hardcoded (eg:Animal animal=new Cat()) or the solutions don't mention where the "what to do" from. What if my "what to do" is from dynamic data? eg:
public static void main(String[] args) {
try{
Animal animal = (Animal)(Class.forName("mypackage."+args[0]).getConstructor().newInstance());
animal.print();
}catch(Exception e){
e.printStackTrace();
}
}
is it still worth to replace it with polymorphism? Also I found sometimes the input name is not exactly the same as my desired class name, for example, the incoming data may use an int to represent the type (which the data source is from other API instead of my projects that under my control), so I need to modify the code like this:
public class Animal_0 implements Animal{
public void print(){
System.out.println("cat");
}
}
public class Animal_1 implements Animal{
public void print(){
System.out.println("dog");
}
}
public static void main(String[] args) {
try{
ConfigObj config=(some system function to get config); //0 = cat, 1 = dog
Animal animal = (Animal)(Class.forName("mypackage.Animal_"+config.animalType).getConstructor().newInstance());
animal.print();
}catch(Exception e){
e.printStackTrace();
}
}
Is it still worth to use polymorphism in this case?