mercredi 20 avril 2016

Design pattern choice

It's often the case that I have a possible action, and I need to select among different ways to do it. Note that through the lifetime of the object, I will need to run the method only once.

One way to do it could be:

class A(object):
    def my_fun(self, identifier, *args, **kwargs):
        if identifier == 'fun1':
            return self.fun1(*args, **kwargs)
        elif identifier == 'fun2':
            return self.fun2(*args, **kwargs)
        ...

    def fun1(...):
        ...
    def fun2(...):
        ...

Another way that I think is nicer is to directly set the method:

class A(object):
    def my_fun(self, identifier, *args, **kwargs):
        raise NotImplementedError()

    def fun1(...):
        ...
    def fun2(...):
        ...


a = A()
a.my_fun = fun23

I think it's nicer because there is a lot less boilerplate code, adding a fun is just implementing it, rather than adding it as well in the my_fun. Also I can have a proper autocomplete when choosing the function.

However, I have not seen this way of doing things in other python code. Is it good practice? Are there other suggestions for doing this?

Aucun commentaire:

Enregistrer un commentaire