mardi 30 août 2016

What's the correct way to access methods of a member variable in a class pointing to an object?

What's the correct way to define/access methods of a member variable in a class pointing to an object?

For e.g.,

I've a class Foo that has a method bar. class Foo: def bar(self): return 'bar'

Now, in another class Bar, I'd like to store an object to this class (I do not want Bar to inherit Foo).

What's the correct/recommended way to define class Bar?

class Bar:
    def __init__(self):
        self.foo = Foo()

OR

class Bar:
    def __init__(self):
        self.foo = Foo()

    def bar(self):
        return self.foo.bar()

The former will allow me to use: x = Bar() x.foo.bar()

But, with this I'm directly accessing methods of a member variable (strong coupling).

The benefits I see with this approach are:

  • I don't have to wrap every new method that gets added to class Foo.
  • Bar may contain more member variables pointing to other classes. Not wrapping them keeps Bar smaller and manageable in size.
  • The auto-completion facility from IDE (pycharm, etc.) or ipython helps look an object of bar like a menu (x.foo) followed by a sub-menu (x.foo.bar(), x.bat.foobar(), etc.) making it easier to develop code.
  • Functional programming look-n-feel (not sure if this a pro or con)

The cons are strong coupling, not encapsulating internal details of foo, etc.

I wanted to check if this a recommended practice? And/or if there are any guidelines related to this (kind of implementing a composite pattern)?

Any inputs/pointers will be highly appreciated!

Aucun commentaire:

Enregistrer un commentaire