News for hackers. Stuff that matters.
Re:OOP practiced backwards is "POO" by theBobMcCormick on Friday December 10, 2010 @10:15PM (#1994041)
I think the Ruby way wouldn't be ask the object if it's a duck, but rather to ask it responds to the fly method, or the swim method, or maybe even the quack method, etc. In other words, you don't really care if it's a duck, just if it can accept the message you're about to send it.
Re:OOP practiced backwards is "POO" by wrs on Saturday December 11, 2010 @09:01PM (#1996188)
Not "the message you're about to send it", but "the set of messages you might send it". Duck typing is not limited to a single message.

For example, a hash-based collection might require that all its members implement an equality method and a hash method. Typically in Ruby you test this by just waiting for one of those method calls to blow up somewhere in the hash table code. Instead, you could test "acts_like?(Hashable)" -- meaning "reaponds_to?(:=) && responds_to?(:hash)" -- on insertion. Then you could give a nice, meaningful error message at a nice point in the code.

Note that this has nothing whatsoever to do with is_a?, which is the important difference between this and type-based interfaces as in Java.

Re:OOP practiced backwards is "POO" by theBobMcCormick on Sunday December 12, 2010 @09:22PM (#1998968)
Absolutely. That's exactly what I wanted to say, stated far better than I could. :-)
Re:OOP practiced backwards is "POO" by limmeau on Saturday December 11, 2010 @05:46AM (#1994613)
So you're checking if it implements an intersection of single-method ducktypes. Now if only there was a way to reify that intersection and give it a name...
Re:OOP practiced backwards is "POO" by steveklabnik on Saturday December 11, 2010 @10:54AM (#1995012)
... but this isn't done very often, and is generally considered a Bad Idea, so let's not encourage it with a special language construct.
Re:OOP practiced backwards is "POO" by limmeau on Saturday December 11, 2010 @02:14PM (#1995439)
What exactly is the bad idea here? Having more than one method in a duck-type?
Re:OOP practiced backwards is "POO" by steveklabnik on Saturday December 11, 2010 @02:36PM (#1995482)
is_a? and respond_to? are code smells.
Re:OOP practiced backwards is "POO" by limmeau on Saturday December 11, 2010 @04:40PM (#1995719)
Yes, I agree. I wasn't actually suggesting to sprinkle instanceof-checks throughout the code.

What I was trying to get to: if you accept the existence of single-method ducktypes (like "things that have a walk() method" oder "things that have a quack() method"), then by intersecting these concepts, you arrive at things just like interfaces, whether you call them interfaces or not. If you want the pond system to work with your two-legged bird-sound robot, you perform the same mental steps as when implementing an interface. Hence, ducktypes could be seen as interfaces without an instanceof-operation.