Friday, July 20, 2012

Inheritance versus composition: When should you use inheritance?

The answer is: NEVER.

In Python.



In inheritance, it's very hard to follow the flow.

In composition, you get lines like the below:

import sequence1
import sequence2
import somemodule

sequence1.dosth()
sequence2.doanotherthing()
somemodule.qwer()

and if you don't like something, you can see it immediately, and you can swap it out.


In inheritance:

def somemethod(self):
    super(ThisClass,self).somemethod() # what the hell does the base class do here that you should repeat here, anyway?

What if you wanted to put in something between the lines of what the base class is doing in somemethod() ?
To override it, while still desiring the behaviour conveniently given to you by the base class, you would have to paste the whole source code of somemethod() of the base class in order to slot in something (esp. for debugging).

Have encountered this many times.




Inheritance versus composition: Which one should you choose?

A comparative look at two fundamental ways to relate classes



http://www.javaworld.com/jw-11-1998/jw-11-techniques.html



In Python, you NEVER need to pass in a variable to some function that 'expects' a certain object Type, so, the answer is, you NEVER have to use Inheritance, only composition.


The problem with inheritance is that it too tightly couples a certain functionality to - an object Type:

= it becomes hard to SWAP* out something.

and when you create a new instance of a subclass, you are forced to get everything that is in the long chain of ancestor classes, which you never use.

And you never even need to know.
Or if you need to know, you have no way of knowing.

You find yourself copy pasting whole blocks of code from the parent classes to override the methods, you know there is something wrong already with the design. Being so unwieldly.

However, you can manage this and just move forward with the behaviours.




Python modules are better at grouping together items of related functionality,
and they can be easily swapped out or not included to be used, change their implementation,

in other words, better API can be written using composition. From experience.



* SWAP: You like this one the best... I swapped n units of XXXXX? for p units of YYYYY? ^v^ Jangan marah ya? ^o^






The conclusion is, when we work to get other people's money, we need to work with whatever code is thrown to us, and somehow already has 60-90% of the desired behaviour,

so we can't just throw everything out and do a rewrite (most of us rather eat glass than to do so.)

Instead, try to manage it, and if the originator is sitting right next to us, OPEN YOUR MOUTH and ASK them HOW !!! (Rather than trying to figure it out all by yourself... that is a proof of stupidity more than cleverness.)

No comments:

Post a Comment