Trans posted a reply to my article saying that I was being too hard on
is_a?/kind_of? I responded there but thought that I should repeat
what I said here:
I think you’re a little too hard on is_a?/kind_of? though. I don’t
think they fit the “chicken” typing character quite as well. Yes, they
aren’t 100% in a dynamic language such as Ruby’s, however they are
much much more dependable than respond_to? b/c modules and class
intend to represent an encapsulation of behavior. If we ask ‘is_a?
Enumerable’, we can be pretty sure that we are working with something
that responds to #select or what have you as the way we’d expect.
True enough, but I wouldn’t say much more dependable. Even within an
implementation hierarchy, the signature and even the meaning of a
method can change. Consider, for example how the details of the each
method vary depending on whether the enumerable is, say, a Hash, vs.
an Array. You’re typically expecting certain things to be yielded to
the block by each, and neither kind_of? or respond_to? helps predict
either the arity for the block expected, or what will be yielded.
And the flip side argument against chicken typing with kind_of? is the
false negative problem. There are interesting cases where unrelated
classes implement similar methods or families of methods.
And sometimes the method similarity can be complex, making determining
substitutability difficult. Consider how many classes implement some
form of , and how many variations of parameters there are affecting
the semantics, even within the same class.
While some of the chicken typing persuasion might look at this as a
mess needing to be cleaned up, duck typers see it as the powerful
flexibility that gives Ruby it’s agility when coupled with the right
approach and tools.
My blog on Ruby