[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Duck Typing

Austin Ziegler

9/13/2003 2:47:00 PM

On Sat, 13 Sep 2003 18:57:25 +0900, Dan Doel wrote:
> Meino Christian Cramer wrote:
>> If both works: is_a? and respond_to? : What is the advance of one
>> over the other beside the fact, that one has a cool name : "Duck
>> typing"?
>>
>> Is one slower, less clean or ... ? I am just curious...
> You really shouldn't use #is_a? or #respond_to? much at all.
> That's not what duck typing is about.

> Just write your method to use methods that the passed in object
> should have, by the contract of the method. Then test to make sure
> your program works.

However, #respond_to? -- which I do use often *as a library writer*
-- is valuable in producing meaningful exceptions. In Text::Format,
I allow you to supply a custom "hyphenator." The hyphenator must
respond to a certain call -- and I think it has to have a certain
arity. If it doesn't, when you're adding the hyphenator to the
formatter object, I raise an exception. I don't check when I'm
[b]running[/b] the code, becauuse I know any object provided will
have this hyphenator.

I will also use #kind_of? (#is_a?) when I need to distinguish
between an Array, a Hash, a String, and a Numeric. Once we're above
that level of operation, I tend to use duck typing.

-austin
--
austin ziegler * austin@halostatue.ca * Toronto, ON, Canada
software designer * pragmatic programmer * 2003.09.13
* 10.42.31