word. http://c2.com/cgi/wiki?DuckTyping
my initial impression of "duck typing" was equivalent to dynamic
typing, but there seems to be a little more to the mallard definition.
i would appreciate an example of code demonstrating how to introspect
a "hey, what kind of object are you?" message/method.
In essence, I don't: I don't ask what class and object is, I tell it to
represent itself as one when it's important, and just ignore it
otherwise:
not duck typed:
def foo(s)
raise TypeError if !s.kind_of? String
frob(s) << "thing"
end
duck typed:
def foo(s)
frob(s.to_s) << "thing"
end
and even more so:
def foo(s)
frob(s) << "thing"
end
The last one I can point out a unique property: If frob just adds
something to the end of what it's passed with <<, as well, then for all
intents and purposes, I don't have to care whether the parameter is a
string or a file -- or something else entirely. As long as it supports,
in this case, <<, it's all good. I just don't bother checking.
Part of what supports this style well is somewhat functional-style
programming: I to make a few more checks when I store something so that
a backtrace won't reveal its origin. Then, in my code, I try to avoid
needing to store things often.
Good examples of this are WEBrick and many of the other standard
libraries: WEBrick's state is mostly transitory, with a request built,
then passed from method to method as parameters, building a response
which is ultimately returned. Nowhere does the response go into an array
for later retrieval, no queue or anything like that. It melds very well
with duck typing, too -- the response has to respond to a handful of
easily-discoverable methods, and there aren't many odd cases where a
method gets called in only a few situations.
Ari