[Python-3000] Abilities / Interfaces
Phillip J. Eby
pje at telecommunity.com
Wed Nov 22 19:23:42 CET 2006
At 09:24 AM 11/22/2006 -0800, Bill Janssen wrote:
>I seem to spend a lot of time inside functions looking over values and
>figuring out what to do do with them, actions which don't involve
>invoking further functions, but rather operating directly on those
>values in different ways.
Whereas to me, that's an antipattern because that makes your code closed to
extension. What if somebody has a new kind of object that you didn't
anticipate? Interfaces don't solve the problem, they just kick it up to
another level of abstraction, like hiding the dirty laundry under the rug.
The real problem here is that type inspection violates encapsulation and
the whole point of being "object-oriented" in the first place. The point
of OO is that it lets you *hide* the implementation. If you put the
implementation in an if-then branch, you've just lost your OO-ness.
The reason it's *tempting* to do this in Python, is because we have so many
convenient built-in data types that don't have application-specific
methods. In Java, where you have to create new types every time you turn
around, and have method overloading anyway, you don't *do* this kind of
type inspection. It gets handled by type dispatching -- a primitive sort
of compile-time only generic function! It's considered bad style to write
a huge block of 'ob instanceof IFoo' tests in Java, when you can just write
overloaded methods.
In Java, SMTP.sendmail would be something like this (using Python-like
syntax 'cause my Java is rusty):
def sendmail(self, from, to_addrs:str, msg, ...):
return self.sendmail(from_addr, [to_addrs], msg, ...)
def sendmail(self, from, to_addrs:list[str], msg, ...):
# main implementation
So, what I've been trying to say is that I don't think it's a good idea to
copy Java interfaces without also copying the machinery that allows you to
avoid 'instanceof' spaghetti.
More information about the Python-3000
mailing list