vendredi 20 septembre 2019

Mask a return from an annonymus object method as a getter for another object

Sorry for the horrible title, not clear how to express this in words, hence the code of the pattern:

class OtherClass:
    def __init__(self, parameter):
        # Do stuff to prepare for calling get_attribute
        pass
    def get_attribute(self):
        return "Something valuable"

class SomeClass:
    def __init__(self):
        self.attribute1 = None

    def get_attribute(self):
        return OtherClass(self.attribute1).get_attribute()

if __name__ == "__main__":
    my_class = SomeClass()
    result =  my_class.get_attribute()
    print(result)

I keep noticing this pattern in an inherited codebase and I can't seem to figure out what is the benefit of this approach. As far as I can tell, it's introducing an object to do something that a function could do.

class SomeClass:
    def __init__(self):
        self.attribute1 = None

def get_attribute(parameter):
    # Do stuff
    return "Something valueable"

my_class = SomeClass()
result =  get_attribute(my_class.attribute1)
print(result)

Is this a design pattern with benefits I'm failing to understand? Or just a byproduct the language allowing you to do the same thing in multiple ways?

Aucun commentaire:

Enregistrer un commentaire