On Tue, Oct 20, 2015 at 6:50 PM, Steven D'Aprano email@example.com wrote:
On Wed, Oct 21, 2015 at 09:50:21AM +1100, Chris Angelico wrote:
To me, this is the biggest benefit of inheritance: you do NOT have to predict what someone might want to do. I can subclass someone else's object and change how it works.
I think this is wrong. I think that in general you need to have a fairly good idea of the internal workings of the class before you can inherit from it. Otherwise, how do you know what methods need to be overwritten?
Right. Chris's thinking recalls the reason why inheritance at some became popular (I guess it was in the '90s). Steven explains (in the part that I've cut) why many experts have soured on it quite a bit.
Personally, I happen to think that inheritance is often useful when a number of classes are designed together (typically all at once and belonging to the same library) and also occasionally when a base class is explicitly and carefully designed to be inherited (there are beautiful things you can do with the template pattern, for example). But inheriting from an implementation that wasn't designed with your use case in mind is often asking for trouble -- if not now, then in the future when a refactored implementation is released.
You might interject, that's the fault of the implementation refactoring -- they didn't properly think about interface compatibility. But while it's usually easy enough to keep an interface compatible where it's just the user calling methods on the implementation, the "interface" presented by subclassing is much more complex -- you would have to specify exactly which method's implementation calls which other method, and you'd also have to ensure that the object is in a sane state when it calls that other method, because it *could* be the case that the latter is overridden by a subclass. It's terribly fragile, and better avoided.