My views on inheritance versus interface

December 9, 2009

Due to some recent entries, I've been thinking more about inheritance and interfaces and I've come around to a particular view, which you could call either the duck typing view or the jaundiced C programmer's view. Put simply:

Interfaces are what you should care about from outside a module. Inheritance is, or should be, strictly an implementation issue for inside the module, except when inheritance is the simplest way to expose certain functionality for reuse by the outside world.

(In Python, Exception is one example of such exposed functionality.)

In (strictly typed) languages with neither duck typing nor explicit interfaces, you have no choice but to use inheritance as a standin for interfaces, but this is an artifact of the language's limitations; it's not a desirable state in general. In languages with explicit interfaces, you can use them directly. In a language with duck typing, you should use that or construct an interface system yourself.

I further think that insisting on using inheritance when you really meant interfaces places you on a collision course between two opposing view of how much freedom sub-classes have to modify the functionality of their parent class. If inheritance is interface, it makes sense to rigidly lock down parent class behavior against modification by children; you are enforcing the interface. If inheritance is exposing functionality, it makes just as much sense to allow sub-classes more freedom, even if this means that they could potentially do things that would violate assumptions that are relied on by parent methods.

In a duck typed language, insisting on using inheritance as an interface still exposes you to this conflict. As a result, it significantly constrains the freedom of the module implementor and adds to their work; they must now document and support how to do things with their 'interface' classes, and once they do this their freedom to revise the class implementation is limited to what they can do around the edge of the (public) documentation.

Since using inheritance this way isn't necessary in a duck typed language, I thus believe that doing so is a mistake; it imposes unnecessary costs. (Worse, the costs are not necessarily born by the people clamouring for the ability to do this, since they are not usually the module author.)

Written on 09 December 2009.
« Why I am not enthused about etckeeper and similar systems
How not to copy a file to standard output in Python »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Wed Dec 9 02:13:19 2009
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.