From: <dblack / candle.superlink.net>


> I've always had a fondness for inheriting from Array and
> Hash... though, you point out in your example, it can be overkill,
> leaving an object with methods that really have nothing to do with it.
> But sometimes the fit is rather good -- those core classes are core
> for good reasons.  I've never thought of it in terms of claiming that
> there's a new kind of Array or Hash; I see it more as just
> incrementally building on the available components of the language.

I used to inherit from HashMap in Java occasionally, but it always felt dirty.
It's great to built on the language's components, but inheritance isn't the
only way to build.  That's one of my great realisations from Ruby.  Inheritance
used to be the path of least resistance.  Now I treat inheritance as a
significant design decision that has to be justified.  I use it less than
before, thus when it is used, its purpose is more clear.


> > In Jim's case, he wanted to add some methods to Matrix.  Well, he didn't
want
> > to change Matrix directly, but the methods he was going to add would in no
way
> > be out of place in the real Matrix class, so to me, inheritance is the
wrong
> > approach.  Delegation is the key here.  Create a new class based on Matrix,
add
> > your methods, and forget that Matrix ever existed.
>
> I spot an opportunity to learn more about delegation, something which
> I've never really absorbed.  Can you elaborate a bit on the conditions
> under which delegating would be a better choice than inheriting in
> this example?

Well, I think of inheritance as specialising a class (as in Car < Vehicle).
You encapsulate objects when you want to make use of them (so a Stack
encapsulates an Array, as does a Matrix).  I think of delegation as wholesale
encapsulation - you want to use *all* of an object.  Thus, delegation provides
all the methods you want, and gives you the opportunity to build on them.  I
was hoping to provide an example, but it's getting very late and I'm fighting
with the syntax.

Wholesale delegation and inheritance are only subtly different.  I'd like to
hear if you have reason to prefer inheritence in these situations.  The Pickaxe
reference section has some interesting examples on delegation.

Cheers,
Gavin