3 ms·
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 met
by theBobMcCormick 16y ago
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.
- limmeau 16y agoSo 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...
- steveklabnik 16y ago... 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.
- limmeau 16y agoWhat exactly is the bad idea here? Having more than one method in a duck-type?
- steveklabnik 16y agois_a? and respond_to? are code smells.
- limmeau 16y agoYes, 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.
- wrs 16y agoNot "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.
- theBobMcCormick 16y agoAbsolutely. That's exactly what I wanted to say, stated far better than I could. :-)