[Python-ideas] Batty idea of the week: no implementation inheritance
Neil Toronto
ntoronto at cs.byu.edu
Thu Jan 10 02:25:10 CET 2008
It occurred to me that every problem I've had with object-oriented
programming stems from the fact that subclasses implicitly inherit
implementation details from their parent classes. It also occurred to me
that I've never solved a problem with implementation inheritance that
couldn't be done via composition and delegation approximately as easily.
This kind of delegation would be similar to subclassing:
class A:
def foo(self):
# do something cool
class B: # Not a subclass of A, but acts like one
def __init__(self):
self.a = A()
def foo(self):
# do something before
ret = self.a.foo()
# do something after
return ret
# or foo = A.foo for simple cases?
For lack of a better term (I'm probably just not well-versed enough in
language theory) I'll call it reverse delegation. The big UI difference
between this and subclassing is that here A retains control over its
implementation and its writer doesn't have to worry about whether
changing anything will break subclasses - because there aren't any.
There's also forward delegation for when a class doesn't want to care
about how something is implemented:
class A:
def __init__(self, barimpl):
self.barimpl = barimpl # or gets it by some other means
def bar(self):
return self.barimpl.bar()
class B:
def bar(self):
# do something cool
For some reason this gets called "dependency injection". (I know why,
but IMO it's a horrible name.) It's typical OO practice to solve the
same problem by defining A.bar as abstract, though it's increasingly
frowned upon in favor of forward delegation / dependency injection.
It occurred to me that this sort of thing would work perfectly with duck
typing, and even duck typing plus something like Java's interfaces. In
the first example, as long as A and B have the same interface they could
each pass the same type checks. In the second, A could define an
interface containing bar (or more) and accept anything implementing it.
The big downside to both delegation types is that they're wordy,
especially with interfaces added. With the right syntactic support (I
admit I haven't given this much thought) it might be as nice as
implementation inheritance. I also have a niggling feeling that I'm
missing something, especially with regards to multiple inheritance,
though I've never understood what the big deal was with that past
inheriting an interface or convenient mixins.
Neil
More information about the Python-ideas
mailing list