Duck Typing

J

Jim Weirich

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?
 
G

Gavin Sinclair

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
 
H

Hal Fulton

Meino said:
From: (e-mail address removed)
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 !




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
 
D

Dan Doel

Meino said:
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
 
M

Martin DeMello

Dan Doel said:
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
 
J

Jason Creighton

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


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
 
R

Ryan Pavlik

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

Ryan Pavlik

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

Dan Doel

Ryan said:
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
 
D

Dave Brown

: > 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
 
M

Martin DeMello

Ryan Pavlik said:
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
 
R

Ryan Pavlik

On Sun, 14 Sep 2003 15:22:37 +0900

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 <[email protected]>

"That's just horrible fanged death from the briny
depths of the sea attempting to kill us. Pay it no
mind." - 8BT
 
M

Martin DeMello

Ryan Pavlik said:
On Sun, 14 Sep 2003 15:22:37 +0900



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
 
M

Mauricio Fernández

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
 
A

Alex Martelli

Luc said:
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
 
K

Kent Dahl

Alex said:
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*
 
R

Robert Klemme

Ryan Pavlik said:
On Sun, 14 Sep 2003 15:22:37 +0900



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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top