Hi --

On Mon, 21 Jul 2008, Robert Dober wrote:

> On Mon, Jul 21, 2008 at 2:37 PM, David A. Black <dblack / rubypal.com> wrote:
>> Hi --
>> For true duck typing you would just do:
>>
>>  s.the_method
> In the general case thats seems clumsy to me, I'd rather check if a
> protocol is implemented. A very simple example is an IOArray I use to
> capture output, it mocks two file methods #puts and #<<.
> What would you prefer?
>
> raise Whatever unless o.replies_to?( :puts ) && o.replies_to?( :<< )
>
> raise Whatever unless o.implements_behavior? IOArray # but the name is bad

In general, I'd prefer:

   obj.<<   # Rescue at this point, not before.

It depends, though. I could imagine a situation where you really don't
want to proceed until you've got at least some assurance that an
object will respond as you want, because you're going to change some
state in another object. I wouldn't like to see everything wrapped up
in response checks.

> Now imagine the protocol has five or even 10 methods?
>
> Maybe it might also be helpful to recall the definition of duck
> typing: "If it walks like a duck and talks like a talk...", this is
> about behavior and not about methods.

Here's the thing, though. It is possible to do this:

   obj.some_method

or this:

   if obj.respond_to?(:some_method)
     obj.some_method
   end

or this:

   if obj.is_a?(Thing)
     obj.some_method
   end

or this:

   if obj.implements_behavior?(Stuff)
     obj.some_method
   end

etc. I've always understood duck typing to mean the first. I've also
described the first as "hard" duck typing and the second as "soft"
duck typing. Rick DeNatale makes a similar distinction between duck
typing and "chicken typing".

But in the end, it's got to be about what each of us likes to write in
our programs. It's not like the one that gets called "duck typing" by
the most people will suddenly be better than all the others in all
circumstances :-)


David

-- 
Rails training from David A. Black and Ruby Power and Light:
     Intro to Ruby on Rails  July 21-24      Edison, NJ
  *  Advancing With Rails    August 18-21    Edison, NJ
  * Co-taught by D.A. Black and Erik Kastner
See http://www.rubypal.com for details and updates!