(original) (raw)
2014-03-15 21:44 GMT+00:00 Nikolaus Rath <Nikolaus@rath.org>:
Guido van Rossum <guido@python.org> writes:It wasn't known to me until now. Are these downsides described in some
\> This downside of using subclassing as an API should be well known by now
\> and widely warned against.
more detail somewhere?
The short version is: "inheritance breaks encapsulation".
As a trivial and stupid example, let's say you need a list object which counts the number of items inserted/removed (it's completely stupid, but that's not the point :-):
So you might do something like:
"""
class CountingList(list):
� � \[...\]
� � def append(self, e):
� � � � self.inserted += 1
� � � � return super().append(e)
� � def extend(self, l):
� � � � self.inserted += len(l)
� � � � return super().extend(l)
"""
Looks fine, it would probably work.
Now, it's actually very fragile: imagine what would happen if list.extend() was internally implemented by calling list.append() for each element: you'd end up counting each element twice (since the subclass append() method would be called).
And that's the problem: by deriving from a class, you become dependent of its implementation, even though you're using its public API. Which means that it could work with e.g. CPython but not Pypy, or break with a new version of Python.
Another related problem is, as Guido explained, that if you add a new method in the subclass, and the parent class gains a method with the same name in a new version, you're in trouble.
That's why advising inheritance as a silver bullet for code reuses is IMO one of the biggest mistakes in OOP, simply because although attractive, inheritance breaks encapsulation.
As a rule of thumb, you should only use inheritance within a module/package, or in other words only if you're in control of the implementation.
The alternative is to use "composition"
For more details, I highly encourage anyone interested in looking at the book "Effective Java" by Joshua Bloch (the example above is inspired by his book). Although Java-centric, it's packed with many advises, patterns and anti-patterns that are relevant to OOP and just programming in general (it's in my top-5 books).
cf