Polymorphism without eval can simplify the description of branches, but it cannot eliminate it. Eval can be used to eliminate branch nesting, but it's scary → Oh, I can't instantiate it with python's eval (I'll check it soon)
Polymorphism for eliminating general branching seems to cause branching at the time of object creation. When polymorphism is applied, the description of branching becomes lighter, so it is possible to argue that the original purpose of improving maintainability has been achieved, but the effect cannot be realized. There is an idea to do something like eval at the time of object creation in order to completely break the branch, but I am vaguely anxious about eval. I would like to hear your opinions about this area. The following is polymorphism or duck typing, but the same thing is said.
switch.py
#There is a branch in the first place
request = param #param contains the parameters in the request and the assumed Dog and Cat
if request == "Dog":
print "wan"
elif request == "Cat":
print "nya-"
polymorphism.py
#There is a branch at the time of object creation
class Dog:
def foo(self):
print "wan"
class Cat:
def foo(self):
print "nya-"
def make(animal):
if animal == "Dog":
return Dog()
elif animal == "Cat":
return Cat()
request = param #param contains the parameters in the request and the assumed Dog and Cat
animal = make(request)
animal.foo()
polymorphism_eval.py
#No branch
class Dog:
def foo(self):
print "wan"
class Cat:
def foo(self):
print "nya-"
request = param #param contains the parameters in the request and the assumed Dog and Cat
animal = eval(request+"()")
animal.foo()