When is a subclass not right?

David Ells ells.david at gmail.com
Fri Aug 25 15:12:34 EDT 2006


Carl Banks wrote:
>
> I think it's kind of a fine point.  In my own code I've had cases where
> I've switched from subclass to attribute and back over the development,
> and vice versa.  I think there are many cases where it's preferable to
> use an attribute, but not really wrong to subclass (and vice versa).
>
> The classical advice in choosing whether to subclass or or use
> attribute is whether its more an an "is a" or "has a" relationship.  If
> it's more natural to say B is an A, then subclass.  If it's more
> natural to say B has an A, then use an attribute.  But that's only a
> rule of thumb.
>
> I personally find another question helpful.  If it's reasonable that B
> could have more than one of A, regardless if it actually does, use an
> attribute.  If it's unreasonable, subclass.  Again, rule of thumb.
>
>
> Carl Banks

This is not always the defining line between when to use inheritance
vs. when to use composition. It is of course the way to decide among
the two in the situation of 'has a' vs. 'is a', i.e. a car with an
engine instance ( a car has an engine) vs. a ford mustang engine which
is an engine. But even in the second case, you may not automatically
want to use the built in language inheritance, like class B1(A).
Instead, you may want to use a private instance of the super class and
delegate calls from the subclass to it, in order to preserve the
abstraction barrier that the interface of the super class has put up.
Then a ford mustang engine, which is still an engine, is simply a class
with a private engine instance that delegates the appropriate calls to
that instance. The rule of 'has a' and 'is a' still holds, but there is
also more than one way to do inheritance (language-facilitated vs.
composition), and while this would normally be a peripheral point, this
is basically what the O.P. was asking about (i.e. the difference
between classes B1 and B2, and how they go about subclassing A).




More information about the Python-list mailing list