Inheritance vs composition in this example

Posted by Gerenuk on Programmers See other posts from Programmers or by Gerenuk
Published on 2012-09-01T09:47:27Z Indexed on 2012/09/01 9:49 UTC
Read the original article Hit count: 292

I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.

In particular my example was

Inheritance:

class Do:
    def do(self):
        self.doA()
        self.doB()

    def doA(self):
        pass

    def doB(self):
        pass

class MyDo(Do):
    def doA(self):
        print("A")

    def doB(self):
        print("B")

x=MyDo()

vs Composition:

class Do:
    def __init__(self, a, b):
        self.a=a
        self.b=b

    def do(self):
        self.a.do()
        self.b.do()

x=Do(DoA(), DoB())

(Note for composition I'm missing code so it's not actually shorter)

Can you name particular advantages of one or the other?

I'm think of:

  • composition is useful if you plan to reuse DoA() in another context
  • inheritance seems easier; no additional references/variables/initialization
  • method doA can access internal variable (be it a good or bad thing :) )
  • inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object
  • inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton
  • ...

Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is prefered, but I'd like to understand that by example.

Of course I can always start with one and refactor later to the other.

© Programmers or respective owner

Related posts about object-oriented-design

Related posts about inheritance