samedi 2 mars 2019

Getting rid of the `if` statements when creating dynamic subtypes

Its a question mainly about design.

Lets suppose we have a class that has the role of initiating different subclasses of a certain type by some parameters that it is iterating through. The problem comes when the __init__ method receives different parameter for each subtype. Is there any way to avoid the if statements inside the function that initializes the classes just to know what parameters to pass in? Maybe some design pattern that I am not aware of. Or is it an outcome of a bad design?

below is an example of what I mean. notice the manage static method that has the if...else... in it and if there were more types of workers, we would have more if's, which is what I am trying to avoid.

from abc import ABCMeta


class BaseWorker(metaclass=ABCMeta):
    def work(self):
        pass


class Worker1(BaseWorker):
    def __init__(self, name):
        self.name = name

    def work(self):
        pass


class Worker2(BaseWorker):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def work(self):
        pass


class Manager(object):
    @staticmethod
    def manage(attributes_list):
        for attributes in attributes_list:
            if "age" in attributes:
                w = Worker2(name=attributes["name"], age=attributes["age"])
            else:
                w = Worker1(name=attributes["name"])
            w.work()


if __name__ == '__main__':
    dynamic_attributes = [
        {"name": "davay"},
        {"name": "ok", "age": "55"},
        # and so on...
    ]
    Manager.manage(dynamic_attributes)


And the desired solution would have been

    @staticmethod
    def desired_manage(attributes_list):
        for attributes in attributes_list:
            w = worker_factory(attributes)
            w.work()

** Notice that the worker_factory is just an arbitrary name for the way that will solve this issue, it doesn't mean that factory pattern is the way to go. Even less, if we try factory pattern, from what I can see, the if statements will just move there and it wont solve anything.

Thanks!

Aucun commentaire:

Enregistrer un commentaire