Duck Typing

Discussion in 'Ruby' started by Jim Weirich, Sep 13, 2003.

  1. Jim Weirich

    Jim Weirich Guest

    In the Method Redefinition thread, this explanation of Duck Typing is
    offered ...

    > What Duck typing is based mostly on realising what sort of operations
    > you want to do with the object and testing for those operations,
    > rather than testing for the class. As Dave is fond of saying: type and
    > class aren't the same.


    This is slightly different than my understanding of Duck Typing. I
    would phrase it more like this:

    Duck typing is based mostly on realising what sort of operations
    you want to do with the object and just doing them, rather than
    worrying if the object inherits from the proper base class or
    interface.

    I've heard others also explain duck typing in terms of explicitly
    testing for particular methods and I feel that leaves the wrong
    impression. If we say Ruby supports duck typing, then newcomers are
    left with the impression that you need to do a lot of testing for
    particular methods (which you don't).

    I would call this an example of Duck Typing ...

    class Dog
    def talk
    puts "Woof"
    end
    end
    class Duck
    def talk
    puts "Quack"
    end
    end
    [Dog.new, Duck.new].each { |a| a.talk }

    ... even though there is no explicit method testing going on. After
    all, if it walks and talks like a duck ...

    So, am I off base?

    --
    -- Jim Weirich http://onestepback.org
    -----------------------------------------------------------------
    "Beware of bugs in the above code; I have only proved it correct,
    not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)
    Jim Weirich, Sep 13, 2003
    #1
    1. Advertising

  2. On Saturday, September 13, 2003, 10:23:16 AM, Jim wrote:

    > [...]


    > I would call this an example of Duck Typing ...


    > class Dog
    > def talk
    > puts "Woof"
    > end
    > end
    > class Duck
    > def talk
    > puts "Quack"
    > end
    > end
    > [Dog.new, Duck.new].each { |a| a.talk }


    > ... even though there is no explicit method testing going on. After
    > all, if it walks and talks like a duck ...


    > So, am I off base?


    Not AFAIC. Testing for methods is one of those things that can sound
    important in theory, but who ever programs like that? After all, if
    the method you're after isn't supported, what are you going to do?
    Choose another one? ;)

    Of course, in frameworks and libraries there is often some funny
    meta-programming going on, but that's a special case, and it still
    runs on the old assumption that you're confident of what the code is
    doing.

    Gavin
    Gavin Sinclair, Sep 13, 2003
    #2
    1. Advertising

  3. Jim Weirich

    Hal Fulton Guest

    Meino Christian Cramer wrote:
    > From:
    > Subject: Re: Duck Typing
    > Date: Sat, 13 Sep 2003 10:29:52 +0900
    >
    > Hi, first of all: I am very happy to have a programming language with
    > such a communicative and friendly mailinglist!!! :)
    >
    > GREAT!
    >
    > (Whether it will be a good idea or not to mirror the posts into a newsgroup
    > -- we will see. Previously I had made bad experiences, since my email
    > postbox was overloaded with spam. Spammers do scan newsgroups for
    > addresses... but this is quite another topic...)
    >
    > Back to the ducks !
    >
    >
    >>Or even, more generally, left with the impression that there's an
    >>on/off switch: if you say "is_a?" a lot, then you're not doing duck
    >>typing, whereas if you say "respond_to?" a lot, then you are -- when
    >>in fact it's really Ruby that's doing the duck typing, and you're
    >>just deciding how to react to it.

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


    Don't misunderstand. David is saying that this is *some* people's
    impression of what duck typing means.

    Note the second part: "--when in fact it's really Ruby that's doing
    the duck typing, and you're just deciding how to react to it."

    It's not a coding style or technique; it's an attribute of the
    language.

    Hal
    Hal Fulton, Sep 13, 2003
    #3
  4. Jim Weirich

    Dan Doel Guest

    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.

    Excessively using #is_a? and #respond_to? is essentially trying to turn ruby
    from a dynamically typed language into an ad-hoc statically typed language,
    which isn't in the spirit of duck typing at all.

    The only real reason you should be using these methods is if you need to
    take different actions depending on which of several methods is available.
    If you're just checking whether the only method you use exists or not,
    you're
    just doing extra work most of the time. The interpreter will tell you if it
    isn't there.

    It can be a confusing issue if you haven't read the discussions before.
    There
    was a big one some weeks back, so it might be worth it to read the ruby-talk
    archives to clear some stuff up without duplicating all of it again.

    Cheers.

    - Dan
    Dan Doel, Sep 13, 2003
    #4
  5. Dan Doel <> wrote:
    >
    > The only real reason you should be using these methods is if you need to
    > take different actions depending on which of several methods is available.


    Even then, there are cases where you can use the (cleaner or not
    depending on your pov and how many times you have to do it) alternative
    of creating a common name for the methods, and aliasing it to the
    appropriate method within each class. In java terms, you're using open
    classes to retroactively derive from a common interface.

    martin
    Martin DeMello, Sep 13, 2003
    #5
  6. On Sat, 13 Sep 2003 09:23:16 +0900
    Jim Weirich <> wrote:

    > In the Method Redefinition thread, this explanation of Duck Typing is
    > offered ...
    >
    > > What Duck typing is based mostly on realising what sort of operations
    > > you want to do with the object and testing for those operations,
    > > rather than testing for the class. As Dave is fond of saying: type and
    > > class aren't the same.

    >
    > This is slightly different than my understanding of Duck Typing. I
    > would phrase it more like this:
    >
    > Duck typing is based mostly on realising what sort of operations
    > you want to do with the object and just doing them, rather than
    > worrying if the object inherits from the proper base class or
    > interface.
    >
    > I've heard others also explain duck typing in terms of explicitly
    > testing for particular methods and I feel that leaves the wrong
    > impression. If we say Ruby supports duck typing, then newcomers are
    > left with the impression that you need to do a lot of testing for
    > particular methods (which you don't).


    I agree completely.

    > I would call this an example of Duck Typing ...
    >
    > class Dog
    > def talk
    > puts "Woof"
    > end
    > end
    > class Duck
    > def talk
    > puts "Quack"
    > end
    > end
    > [Dog.new, Duck.new].each { |a| a.talk }
    >
    > .. even though there is no explicit method testing going on. After
    > all, if it walks and talks like a duck ...
    >
    > So, am I off base?


    No. That is how I think of Duck Typing as well. Just call the methods.
    Don't bother with method existence checking, Ruby does it for you. (By
    raising NoMethodError)

    Jason Creighton
    Jason Creighton, Sep 13, 2003
    #6
  7. Jim Weirich

    Ryan Pavlik Guest

    On Sat, 13 Sep 2003 17:13:17 +0900
    Hal Fulton <> wrote:

    > > Is one slower, less clean or ... ? I am just curious...

    >
    > Don't misunderstand. David is saying that this is *some* people's
    > impression of what duck typing means.
    >
    > Note the second part: "--when in fact it's really Ruby that's doing
    > the duck typing, and you're just deciding how to react to it."
    >
    > It's not a coding style or technique; it's an attribute of the
    > language.


    I disagree, with some proof by counterexample.

    The assertion is this: Ruby does not have an attribute of the language
    that is "duck typing", it is merely a style of coding.

    1) By the definitions given in this thread, duck typing is taking a
    given object and pretending it's the type you want, and letting
    the language give you an error if it doesn't work like you
    expected.

    (If you disagree with this definition, you can provide an
    alternate one, but arguing over definitions is useless.)

    2) We can accomplish this because the language lets us specify a
    call to a method without checking the type at "compile-time"
    (parse-time, in ruby's case):

    x.a # This call is not validated until it is executed

    3) We can further accomplish this because the language does not
    require we specify types to a methodcall, thus allowing us to
    pass any object.

    4) Statements 2-3 are the only functional provisions necessary for
    accomplishing the practice in statement 1.

    5) Many non-Ruby dynamic languages provide the functionality in
    statements 2-3. Examples include JavaScript, Common Lisp (CLOS),
    Scheme, Python, Perl, and PHP.

    6) These languages make no special provisions for duck typing, but
    it can be practiced, because the functional requirements of 2-3
    are met.

    7) In any of the given languages, and Ruby, one can choose to check
    types or not check types.

    Therefore: Based on statements 1-5, "duck typing" is not specific to
    ruby, but rather made possible by the dynamic nature of a language.
    Based on statements 6-7, duck typing is neither specifically provided
    for nor compulsory, so it is not an attribute of the language.

    Thus, because it can be practiced, or not practiced; in ruby, or in
    other languages; it must be a _style_ available in dynamic languages,
    rather than a specific feature of a particular language.

    --
    Ryan Pavlik <>

    "Damn ye and ye black ops mind games!" - 8BT
    Ryan Pavlik, Sep 13, 2003
    #7
  8. Jim Weirich

    Ryan Pavlik Guest

    On Sun, 14 Sep 2003 04:32:49 +0900
    Michael Campbell <> wrote:

    > > Therefore: Based on statements 1-5, "duck typing" is not specific
    > > to ruby...

    >
    > That was never asserted.


    Yes, but it _was_ asserted that it was a language attribute of ruby,
    when you can practice it in other languages, which have no specific
    provisions, any mention of "duck typing", or common practice thereof.

    (Although, in JavaScript, and most prototype-based languages, you
    usually practice 'duck-typing' because that's the way things are.
    Pure prototype-OOP has no class, just an object that acts in a
    particular manner---in this case, you could probably consider it a
    feature of the language.)

    --
    Ryan Pavlik <>

    "Damn ye and ye black ops mind games!" - 8BT
    Ryan Pavlik, Sep 13, 2003
    #8
  9. Jim Weirich

    Dan Doel Guest

    Ryan Pavlik wrote:

    >Yes, but it _was_ asserted that it was a language attribute of ruby,
    >when you can practice it in other languages, which have no specific
    >provisions, any mention of "duck typing", or common practice thereof.
    >
    >(Although, in JavaScript, and most prototype-based languages, you
    >usually practice 'duck-typing' because that's the way things are.
    >Pure prototype-OOP has no class, just an object that acts in a
    >particular manner---in this case, you could probably consider it a
    >feature of the language.)
    >
    >


    Duck typing may not be a "feature" of Ruby, but it's definitely supported by
    Ruby. It's also very well supported by Python, Perl, JavaScript, and
    I'm sure
    many other languages. The difference with Ruby is that Dave Thomas hangs
    out here more and he's the one who said it originally. :)

    Ruby does have some provisions that make it more supportive of duck typing,
    though. For example, as I understand it, in Smalltalk (which I'm still
    learning),
    you define all your methods when you're building the program, and then all
    that is fixed. You can't, for example, make an object of class Object
    and then
    write custom methods for that one object. So objects and types are more
    dynamic in Ruby than in, say, Smalltalk, for example.

    This, of course isn't exclusive to Ruby. As I recall, JavaScript allows you
    to add methods to arbitrary classes or objects. But, as I said, Dave Thomas
    hangs out here, which is why Ruby people talk about duck typing and
    JavaScript people don't. :)

    Cheers.

    - Dan
    Dan Doel, Sep 13, 2003
    #9
  10. Jim Weirich

    Luc Heinrich Guest

    Mark Wilson <> wrote:

    > I've seen some adoption of the term among python people recently.


    What ? They stole that too ?? :>

    --
    Luc Heinrich -
    Luc Heinrich, Sep 13, 2003
    #10
  11. Jim Weirich

    Dave Brown Guest

    In article <1g18xwi.111fqsa1lnp56oN%>,
    Luc Heinrich <> wrote:
    : Mark Wilson <> wrote:
    :
    : > I've seen some adoption of the term among python people recently.
    :
    : What ? They stole that too ?? :>

    No, it's an invention which is completely original to Guido.
    Sheesh.

    --Dave
    Dave Brown, Sep 14, 2003
    #11
  12. Jim Weirich

    Henon Guest

    On Sat, 13 Sep 2003 09:51:29 +0900, Gavin Sinclair
    <> wrote:

    [...]
    >
    > Not AFAIC.


    [...]

    AWGTHTGTATA
    Are We Going To Have To Go Through All This Again?

    LOL
    --
    - Henon
    Henon, Sep 14, 2003
    #12
  13. Ryan Pavlik <> wrote:

    > Therefore: Based on statements 1-5, "duck typing" is not specific to
    > ruby, but rather made possible by the dynamic nature of a language.
    > Based on statements 6-7, duck typing is neither specifically provided
    > for nor compulsory, so it is not an attribute of the language.
    >
    > Thus, because it can be practiced, or not practiced; in ruby, or in
    > other languages; it must be a _style_ available in dynamic languages,
    > rather than a specific feature of a particular language.


    No, it's related to the question "what is an object's type?" as distinct
    from "what is the class used to instantiate the object?". The phrase
    "duck typing" is no more and no less than a shorthand for "an object's
    type is determined entirely by the set of messages it responds to", by
    analogy with "static typing" (an object's type is determined by a
    compile-time declaration) and arguably as nothing more than a more
    precise way of saying "dynamic typing".

    Any yes, it's by no means specific to Ruby, but it is the way the
    language defines a 'type'.

    martin
    Martin DeMello, Sep 14, 2003
    #13
  14. Jim Weirich

    Ryan Pavlik Guest

    On Sun, 14 Sep 2003 15:22:37 +0900
    Martin DeMello <> wrote:

    <snip>
    > Any yes, it's by no means specific to Ruby, but it is the way the
    > language defines a 'type'.


    No, it's how _you the programmer_ define a 'type'. You have a few
    options here; "duck typing" is just one of them. It has nothing to do
    with what the languages specifies in this case.

    --
    Ryan Pavlik <>

    "That's just horrible fanged death from the briny
    depths of the sea attempting to kill us. Pay it no
    mind." - 8BT
    Ryan Pavlik, Sep 14, 2003
    #14
  15. Ryan Pavlik <> wrote:
    > On Sun, 14 Sep 2003 15:22:37 +0900
    > Martin DeMello <> wrote:
    >
    > <snip>
    >> Any yes, it's by no means specific to Ruby, but it is the way the
    >> language defines a 'type'.

    >
    > No, it's how _you the programmer_ define a 'type'. You have a few
    > options here; "duck typing" is just one of them. It has nothing to do
    > with what the languages specifies in this case.


    The only type checking the language does by default is to (dynamically)
    see if a given object responds to a given message. Checking explicitly
    for responds_to?, is_a? etc. merely add additional restrictions atop
    the type system. By analogy, you could hack the built-in classes so that
    all numbers were strictly integral, but you couldn't say that the
    language was agnostic towards supporting reals.

    martin
    Martin DeMello, Sep 14, 2003
    #15
  16. On Sun, Sep 14, 2003 at 07:19:07PM +0900, Chad Fowler wrote:
    > On Sun, 14 Sep 2003, Ryan Pavlik wrote:
    > class String
    > undef_method :chomp
    > end
    >
    > def some_method(a,b)
    > expect(a, String, b, Numeric) # I'm using your "Strong"Typing module. ;)
    > a.chomp #Whoops! "a" is not the duck you're looking for
    > # (but it *is* a String)!
    > ...etc.
    > end
    >
    > Since I happen to be on the topic of your "Strong"Typing module, let's
    > have a look at the FAQ:
    >
    > <quote source="http://mephle.org/StrongTyping">
    > Q: Yeah, but really, why bother? Why not just let ruby sort out the
    > errors as they occur?
    > A: This is incorrect thinking. Allowing errors to just occur when
    > they happen is naive programming. Consider the following:
    >
    > # Wait N seconds, then open the bridge for M seconds
    > def sendMsg(bridge, n, m)
    > sleep(n)
    > bridge.open
    > sleep(m)
    > bridge.close
    > end



    StrongTyping doesn't address that problem, careful programming does:

    def sendMsg(bridge, n, m)
    open = false
    begin
    sleep n
    bridge.open # either completes correctly or raises an exception before opening
    open = true
    sleep m
    bridge.close
    ensure
    bridge.close if open
    end
    end

    As Chad points out, even StrongTyping assumes that the interface of
    a class will remain stable. This means that as long as methods can be
    removed/modified, the notion of "type" enforced by StrongTyping doesn't
    match Ruby's native one, so you cannot get 100% safety.


    --
    _ _
    | |__ __ _| |_ ___ _ __ ___ __ _ _ __
    | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \
    | |_) | (_| | |_\__ \ | | | | | (_| | | | |
    |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
    Running Debian GNU/Linux Sid (unstable)
    batsman dot geo at yahoo dot com

    'Ooohh.. "FreeBSD is faster over loopback, when compared to Linux
    over the wire". Film at 11.'
    -- Linus Torvalds
    Mauricio Fernández, Sep 14, 2003
    #16
  17. Luc Heinrich wrote:

    > Mark Wilson <> wrote:
    >
    >> I've seen some adoption of the term among python people recently.

    >
    > What ? They stole that too ?? :>


    I would claim independent invention, given that my post of Jul 2000
    to c.l.py where I mused:
    """
    In other words, don't check whether it IS-a duck: check
    whether it QUACKS-like-a duck, WALKS-like-a duck,
    etc, etc, depending on exactly what subset of duck-like
    behaviour you need to play your language-games with. If
    the argument fails this specific-ducklyhood-subset-test, then
    you can shrug, ask "why a duck?" (at least, you can if you're
    a Marx Brothers fan and have memorized "Cocoanuts"' script;
    Monty Python one-true-wayists will have to find their own
    simile here), and move on to the next set of tests (why-a-no-
    chicken immediately comes to mind, but then one would have
    to ask why it crosses the road, so I think we'd better snip it).
    """

    was done before I had ever heard of Ruby, and explained as
    """
    My instinctive approach (and it may be that I still haven't
    developed the "right" Python instincts, because I haven't
    been using it long!)
    """

    while the first mention I can find in comp.lang.ruby is in
    a Jan 2001 post by Ben Tilly:
    """
    Imagine a language where you are constantly telling the
    language everywhere that you have a duck because it is
    walking like a duck and talking like a duck. This is
    built into everything that you do. Then suddenly you
    find out that it isn't really a duck after all.
    """

    Of course, it's quite possible that Google Groups' archive
    is incomplete for either or both languages.


    Alex
    Alex Martelli, Sep 14, 2003
    #17
  18. Jim Weirich

    Kent Dahl Guest

    Alex Martelli wrote:
    > If
    > the argument fails this specific-ducklyhood-subset-test, then
    > you can shrug, ask "why a duck?" (at least, you can if you're
    > a Marx Brothers fan and have memorized "Cocoanuts"' script;
    > Monty Python one-true-wayists will have to find their own
    > simile here), [...]


    I wonder whether Python people will revert to witch-typing, since it
    lends itself so nicely to comparision with duck-typing. ;P

    Not to mention varieties of other old classics:
    - "What kind of typing does your program use?"
    - "Witch typing."
    - "Gah, you grammar nazi. Ok, WHICH kind of typing does it use?"
    - "Witch typing."
    - "I'm asking YOU! Which typing!?!?"
    - "Yes, witch typing."
    - *cue Homer Simpson mode* "Why you little..."
    - *choke, gargle*

    --
    (\[ Kent Dahl ]/)_ _~_ _____[ http://www.pvv.org/~kentda/ ]_____/~
    ))\_student_/(( \__d L b__/ (pre-) Master of Science in Technology )
    ( \__\_õ|õ_/__/ ) _)Industrial economics and technological management(
    \____/_ö_\____/ (____engineering.discipline_=_Computer::Technology___)
    Kent Dahl, Sep 14, 2003
    #18
  19. "Ryan Pavlik" <> schrieb im Newsbeitrag
    news:...
    > On Sun, 14 Sep 2003 15:22:37 +0900
    > Martin DeMello <> wrote:
    >
    > <snip>
    > > Any yes, it's by no means specific to Ruby, but it is the way the
    > > language defines a 'type'.

    >
    > No, it's how _you the programmer_ define a 'type'. You have a few
    > options here; "duck typing" is just one of them. It has nothing to do
    > with what the languages specifies in this case.


    But this is restricted by the language at hand. Because Ruby is the way
    it is, you can decide whether to test an instance's class or you don't -
    but this does not determine how Ruby defines a type. That is fixed by the
    language. You can only decide how you "use" the type system. While in
    Java - to name another popular language - you can't - the compiler
    enforces the type check for you. (Of course, if you use reflection it's
    another situation. But reflection is a special case.)

    Regards

    robert
    Robert Klemme, Sep 15, 2003
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Duck Typing

    , Sep 16, 2003, in forum: Python
    Replies:
    10
    Views:
    680
    Steve Holden
    Sep 17, 2003
  2. Replies:
    15
    Views:
    559
    Isaac Gouy
    Sep 1, 2006
  3. Replies:
    2
    Views:
    318
    Terry Reedy
    Jan 28, 2008
  4. Paddy
    Replies:
    1
    Views:
    389
    Paddy
    May 9, 2008
  5. Paddy
    Replies:
    0
    Views:
    240
    Paddy
    Jun 25, 2008
Loading...

Share This Page