|go ahead... be a heretic|
Re: Inheritance vs Delegation: pros and consby chunlou (Curate)
|on Jul 28, 2003 at 17:56 UTC||Need Help??|
The orthodox teaching is, if it's an a-kind-of relationship, use inheritance; if has-a, use aggregation/composition; if an use relationship, use delegation.
But then, there is design vs implementation. Something could be conceptually inheritance; but delegation implementation could be "better," say, for performance or whatever. (Like, it seems to me not all DBAs favor OO SQL.)
Having to call an instance method through an object that's six or seven levels down the hierarchy is no fun.
The advocacy of the use of inheritance was pretty strong back in the 80's and early 90's. Nowadays, inheritance is more discouraged in many people's teaching in favor of, say, interface (as in Java).
Conceptually and practically, if you think about it, inheritance somewhat violates the very concept of encapsulation. It creates rather strong coupling between classes.
Granted, a change in the parent class automatically cascading to all its children could be a very desirable feature. It's useful when your requirements specification is stable enough. If not, if you need to make dramatic changes in the parents, it could break things everywhere else.
Sure, it breaks things too with delegation or interface, but presumeably since the delegator explicitly indicates which methods to import (and implement), at least, it's clearer where things are going to break.
Not necessarily good or bad, for me, as an development process, if I'm not sure what something is supposed to be for the moment, I tend to prefer to err by using something like delegation until it's rather clear that inheritance makes sense implementation-wise and design-wise (sounds like a backward process in fact).
(There are shove-it-down-your-throat kind of marketing fallacy and disinformation that OOPS and inheritance makes your application and code easier to use. Easy of use is the result of well thought out design and implementation, mostly regardless of the paradigm you're following.)
It could be neat for instance (no pun intended) when you implement a least square regression module, only matrix in, matrix out. Procedural style is fine. But it would be nice when you "print" the result matrix, you get a summary instead of raw data. In that case, you need to overload the double quotes operator. Hence, you need to "bless" your output matrix into an object.
From the user's perspective, the module could look procedural except for the magical "print" feature. From the coder's perspective, the module is technically a bit of OO.
With such a module, inheritance becomes a boot point in Perl, especially since it could have subroutines in a module that aren't object's methods.