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.
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.