Talk:Duck typing
![]() | This article is rated C-class on Wikipedia's content assessment scale. It is of interest to the following WikiProjects: | ||||||||||
|
Identity
[edit]I had no idea this page was a programming related article until I had read half of it. Why not put this kind of information at the top? —Preceding unsigned comment added by 67.163.7.98 (talk) 22:38, 21 September 2007 (UTC)
Cocoa/Objective-C duck typing
[edit]Wouldn't you say that Cocoa and/or Objective-C overall is duck typed? --Devnevyn 14:21, 10 April 2006 (UTC)
- The "informal protocols" described in Objective-C definitely sound like duck typing to me. --Piet Delport 00:10, 25 May 2006 (UTC)
- I thought the same thing right away. --66.37.246.163 19:44, 25 October 2006 (UTC)
- I don't know Objective C, but here is the section on informal protocols from Wikipedia:
- An informal protocol is a list of methods that a class can implement. It is specified in the documentation, since it has no presence in the language. Informal protocols often include optional methods, where implementing the method can change the behavior of a class. For example, a text field class might have a delegate that should implement an informal protocol with an optional autocomplete method. The text field discovers whether the delegate implements that method (via reflection), and if so, calls it to support autocomplete.
- Using the above as an example, If you could successfully substitute a "Russian text field" class with autocomplete method; as well as fail to substitute a "text field" class without an autocomplete method then that would be Duck typing.
- A class changing its behaviour on the absence of a method is not Duck typing. --Paddy 05:30, 13 February 2007 (UTC)
- Yes, but being able to do that does not make it not duck typing. Ruby, for example, uses duck typing, but you could use introspection to work around a missing method (this could be handy if, say, a new version added features, but nonessential ones, so supporting the older versions was OK) --Kinkoblast 19:39, 7 March 2007 (UTC)
- Take the example summer function below, if the summer function has to introspect the values type, and some-how create an appropriate add method for it then that would not be duck typing as the function is manufacturing a missing method for the values/value types. Duck typing is when the summer just calls the same methods as before and whatever arguments to the function already have the required methods. You are not adding methods to the argument types just accepting any arguments that have the right methods. --Paddy 15:11, 11 March 2007 (UTC)
- Yes, but being able to do that does not make it not duck typing. Ruby, for example, uses duck typing, but you could use introspection to work around a missing method (this could be handy if, say, a new version added features, but nonessential ones, so supporting the older versions was OK) --Kinkoblast 19:39, 7 March 2007 (UTC)
- Duck typing, as I understand it from the article, is primarily used in delegates. I edited the article to state this, and added the ‘original research’ template since… well, that's what it is ;-) DanChr 20:39, 1 August 2007 (UTC)
Is Smalltalk duck-typed? Objective-C uses its dynamic dispatching mechanism to achieve duck-typing. If so, then duck-typing is just the result of dynamic dispatching. Under the same hypothesis, CLOS (CommonLisp Object System) generic functions are duck-typed as well.151.47.209.164 (talk) 12:08, 1 June 2009 (UTC)
- Read on :-) --Paddy (talk) 22:06, 1 June 2009 (UTC)
Coined by Dave Thomas?
[edit]According to the RubyGarden wiki's DuckTyping article, Dave Thomas coined the term here, but that's actually just a response to a question about duck typing. (In other words, the term must have already been established by then). Does anyone know of a real source? --Piet Delport 12:57, 20 April 2006 (UTC)
- Weak as it is, as far as anyone knows this is the first instance of him taking credit for coining the term and explaining its meaning; any earlier use is bound to be incidental, and of even less use as a reference. I included it because it's better than no reference at all, but I welcome a better one. Austin Hair ✍ ✉ 13:02, 24 May 2006 (UTC)
There's this post by Thomas which is older, but doesn't actually contain the phrase "duck typing". There's also this one that contains the phrase and seems to attribute it to Thomas. That's the best I can do so far... --Doradus 16:18, 24 May 2006 (UTC)
- Didn't he coin it in a book of his? It would be really great if someone with access can track it down. --Piet Delport 00:01, 25 May 2006 (UTC)
- In his book "Programming Ruby" first edition of 2001 the term does not seem to appear, in 2nd edition of 2005 it features as a title of a full chapter. Hexanen 23:58, 10 November 2006 (UTC)
Alex Martelli used the phrase "the 'walk like a duck' principle" when talking about objects that are "distinct but not different" in this comp.lang.python post from early 2002: http://groups.google.com/group/comp.lang.python/msg/ce158a1940f633c3 -- 11:19, 27 August 2006 (UTC)
- (oh, missed that the matz post discussed above is older than that)
- In comp.lang.ruby, there's another reference by Ben Tilly to the principle one month earlier than Dave Thomas' post mentioned above. The full phrase of 'duck typing' does not appear here either, I first found it in Matz' post of November 2001, cited above. So it appears the phrase starts to surface during 2001. Hexanen 23:58, 10 November 2006 (UTC)
Walks like a duck, quacks like a duck first reference w.r.t. this style of programming
[edit]Alex Martelli in comp.lang. Python answered with this:
"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."
--Paddy 13:43, 11 November 2006 (UTC)
- (The post quoted above is dated Jul 26 2000, 8:00 am). --Paddy (talk) 06:53, 2 June 2009 (UTC)
- There's an interesting, but probably unrelated cite in The Cambridge companion to Shakespearean tragedy (2002). "if it waddles and quacks like a vengeful or ambitious duck, perhaps it is a vengeful or ambitious duck". Conrad.Irwin (on wikt) 20:19, 27 April 2010 (UTC)
- And Shakespears' subject was a programming language?! :-)
--Paddy (talk) 08:47, 28 April 2010 (UTC)
- And Shakespears' subject was a programming language?! :-)
- THis Wikipedia page cites James Whitcomb Riley (1849–1916) [Duck test]
Perl?
[edit]I'm no expert, but doesn't perl use duck typing too? If so, it could be mentioned along with the other languages. 85.0.186.148 00:09, 10 February 2007 (UTC)
- I believe JavaScript / ECMA Script does as well, although I am not an expert either. --24.222.119.254 00:05, 24 February 2007 (UTC)
Confused by what is Duck Typing?
[edit]- Ya gotta have an object system
- Ya gotta have inheritance (for contrast).
- A statement calling a method on an object does not rely on the type of the object, only that the object, of whatever type, must implement the method called.
An example
[edit]you write a function to sum integers in a list like this:
def summer (values, initial_value = 0):
total = initial_value
for value in values:
total = total.add(value)
return total
You normally call the function with a list of integers and the initial value with its default value of zero and are returned the arithmetic sum of those values.
In the language, if strings have an add method that concatenates two strings i.e. 'abc'.add('def') == 'abcdef', then the same summer function can be made to concatenate a list of string fragments, if the initial_value is the null string, .
To the summer function, a list of strings and an initial value of a string looks just like a list of integers and an initial value of an integer; they walk like the ints react ike the ints and so the summer has no trouble treating them like the ints hence Duck typing! Can we remove the expert tag now? --Paddy 16:55, 3 March 2007 (UTC)
Expert tag
[edit]Duck typing is a pretty vauge term, as far as I can tell, and can refer to anything from implicit typing to run-time member-method name checking (to see if the object has a function the program is trying to call). Also, the duck typing of the different listed langauges are significantly different, and I've even heard that the "duck typing" in objective C isn't really duck typing. If anyone thinks this page could do without an expert, I can't imagine they would disagree that the page need lots of cleanup. Fresheneesz 23:11, 4 March 2007 (UTC)
Merge Anonymous type into Duck type
[edit]They are both the same exact thing. One of my hobbies is language and compiler design. A couple of languages as use the concept including BOO and Nemerle, and soon to be included in C# 3.0. With C# 3.0, Microsoft coined the term "anonymous typing" as if it was a new concept but its same exact thing. (I'm on the Mono team so I know a lot about this type of thing) :-) --ZacBowlingtalk 20:19, 17 March 2007 (UTC)
See http://boo.codehaus.org/Duck+Typing --ZacBowlingtalk 19:33, 19 March 2007 (UTC)
- No Anonymous typing is not like Duck typing. Duck typing is not about automagically creating missing methods. Its about methods (and functions), accepting arguments based not on the arguments type but solely on what methods the argument provides. You don't check the type you just call methods on the argument which the argument provides.
- I guess a statically typed language could potentially calculate all the methods that an argument to a method call needs, and then ensure that the argument provides them. But, what happens when an arguments method is called in only one part of a conditional branch?
- As www.theregister.co.uk is quite fond of pointing out, unsubstantiated references to hobbies and interests have been de-valued by some people fabricating impressive references, so, give more examples or retract.
- --Paddy 22:14, 18 March 2007 (UTC)
- um... it has nothing to do with creating with missing methods. Where did you get that from? Duck typing infers the type of a variable based on the first ussage of it (if it looks like a duck, acts like a duck, quacks like a duck, it must be a duck). Anonymous types are the same thing.
- for example, in the statement "var i = 1;", i is inferred as an integer at compile time, in "var x = SomeClass.toString()", x is inferred as a string at compile time so something like "x.substring(1,30)" should work on an upcoming type. Its the same concept in both anonymous types and duck typing. Its also good to note, that with duck typing/anonymous typing its sometimes possible you could say "is instance of" in your language against an interface or class that matches the methods of the type with directly implementing those methods.
- Also my claim about my background is hardly unsubstantiated like the guy who claimed he was professor. See http://go-mono.com/monologue/ where you will find my name on the team list :-)
--ZacBowlingtalk 19:33, 19 March 2007 (UTC)
- Hi Zac, Duck typing does not infer the type of a variable based on its first usage. Not at all!
- You can define a class Duck with methods q1 and q2; class Trance with methods q1, q2 and q3 and class Show with method say.
- There is no inheritance relationship between classes Duck and Trance and Show.
- Let methods q1 and q2 of both Duck and Trance take 'compatible' arguments - lets say no arguments.
- Let method say of class Show, call methods q1 and q2 of whatever instance it has as argument.
- Let method say be originally developed to work with instances of Duck.
- In Duck typing, method say will also work with instances of Trance because Trance supplies every method that say calls.
- In Python (at the command line):
>>> class Duck():
... # Now some Quacks
... def q1(self):
... print "Duck's quack"
... def q2(self):
... print "Duck's quack-quack"
...
>>> class Show():
... def say(self, instance):
... instance.q1()
... instance.q2()
...
>>> duck = Duck()
>>> show = Show()
>>> show.say(duck)
Duck's quack
Duck's quack-quack
>>> class Trance():
... # Answers to queries
... def q1(self):
... print "Whatever"
... def q2(self):
... print "Whenever"
... def q3(self):
... print "Wherever"
...
>>> trance = Trance()
>>> # Here comes the Duck-typing...
>>> show.say(trance)
Whatever
Whenever
>>> # No changing of types involved...
>>> isinstance(duck, Duck)
True
>>> isinstance(trance, Trance)
True
>>> isinstance(duck, Trance)
False
>>> isinstance(trance, Duck)
False
>>>
- I'd like to get the above into the main article. --Paddy 19:27, 20 March 2007 (UTC)
Re-writing page
[edit]I think the Talk section has better examples than the main article, and clears up a lot of misconceptions as to what duck typing is. I intend to re-write the main article this weekend keeping the relevant parts from both the article and the Talk page. --Paddy 05:15, 22 March 2007 (UTC)
My two cents.
[edit]One of the things which often confounds discussions of 'duck typing' is that people want to talk about 'the' duck type of an object, which is a carryover from non-ducktyping systems.
I've been involved with dynamic OO languages for 25+ years, and I have spouted some of my opinions on duck typing in my blog http://talklikeaduck.denhaven2.com/articles/tag/ducks
In my opinion duck typing isn't about the type of an object, but rather about the functional requirements on an object used in a particular context (or role). Any particular object may or may not be usable in a given role. My colleagues and I (who were Smalltalk programmers at the time) used to talk about role-based types long ago, before I ever heard the term duck-typing. Since I came across the term, I've tended to see duck-typing as pretty much the same thing.
An analogy I've used is that duck typing is similar to what happens with an actor is being considered for a part in a play. It's the director, not the actor, who defines the requirements, often in a somewhat fuzzy way. The 'type-matching' occurs through a process of audition. In programming duck-typing is a process of defining roles, looking for, or writing, objects to fill these roles, auditioning these objects (i.e. testing), and possibly refining the role definition. Sometimes/often a role might be written with a particular actor in mind, properly approached however, duck-typing allows the 'play' to be re-staged with a different cast of actors.
As an aside the articles in the Biological Classification Analogy section don't seem to me to be relevant. I'm not sure if they have migrated away from being about evolution based taxonomys, or if there are other better reference. In any case, I think that duck typing, unlike class/inheritance based type systems a la, say C++ is anti-inheritance/hierarchical typing.
Such hierarchical type systems force a particular classification hierarcy on types. While it might seem natural that there is a 'natural' hierarchy of types since we tend to believe that taxonomies in biology or linquistics are somehow real, in fact those taxonomies are often artificial and based on particular viewpoints.
For a biological example, I would point to the Stephen Jay Gould essay "What, If Anything, Is a Zebra?" which, as I recall, describes how the natural definition of a Zebra, i.e. a horse-like animal with black and white stripes, relates to different theories of evolutionary relationships between different species of Zebras in the field.
For linguistics examples, there is Lakoff's "Women, Fire, and Dangerous Things," which has several examples of how speakers of different languages, and members of different cultures, build different categorization hierarchies. Although they might have different views of the hierarchical classification of objects, they can still use those objects according to their perception of the external qualities of individual objects at the base level, which tends to cut across these language/cultural lines. In other words, we tend to use duck typing in everyday life, rather than thinking about implementation hierarchies of the objects we use.
--Rick 14:37, 22 March 2007 (UTC)
In Java
[edit]90% self-flattery. 203.154.48.180 08:43, 14 July 2007 (UTC)
50% self-flatter. User:76.19.113.210 07:24, 2 May 2009 (UTC)
- GREY***
Rewrite
[edit]On 2007-07-12, Dreftymac flagged this article for rewriting:
- this article lacks any foundation of definitional consistency and it reads like a 'free-for-all' mishmash of competing opinions and speculation
I agree with this assessment. —Piet Delport 03:29, 19 July 2007 (UTC)
Much of the problem here is that the "duck typing" concept is usually used to mean the opposite of the "it's a duck" principle. The Martelli usenet posting already cited as a possible first use points this out itself, "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."
It's a bad term! I don't allow its use within my commercial work, because it is so misleading. -Andy Dingley 16:19, 19 July 2007 (UTC)
- I'm thinking along the lines of restricting the definition more in terms of how it is used in Dynamic languages. Languages should have to make dynamic typing easy and normal practice for them to be included. As for 'definitional consistency' that term itself needs explanation :-) .
- Andy - I've never heard of the 'It's a duck' principle? Martelli got it rightas you state.
- Rubyists, Pythoneers, and Perl-mongers know what Duck typing means and use it. Its when the static languages move in with complicated, little used or taught methods that may give some of the functionality of Duck typing, that I should have reverted their entries. --Paddy 18:47, 19 July 2007 (UTC)
- Definitional
- relating to definition; of the nature of a definition; employed in defining.
- Consistency
- a harmonious uniformity or agreement among things or parts.
- As far as ruby, python and perl advocates go, I wish I had ten cents for every "fashionable techie catchphrase" that is supposedly "well understood" among members of a given language community, and yet collapses into dust when you challenge any two experts to independently provide the same (or substantially similar) definition.
- I'm thinking along the lines of restricting this article to referenced and reliable content ... and leaving the fluffy jargon-jockeying on Usenet, where it belongs. dr.ef.tymac 20:15, 19 July 2007 (UTC)
- I'll do you a deal, ten cents to you for every ruby, python and perl advocates "fashionable techie catchphrase". ten cents to me for every Java/XML "fashionable techie catchphrase". ... Just send the balance in an armoured truck --Paddy 07:07, 20 July 2007 (UTC)
- No deal. Just because I singled out python/ruby/perl-ville, doesn't mean I consider Java-land or the people's republic of XML-istan to be any better. Indeed, they're probably much worse. The problem is, these observations still don't give much guidance on how to improve this specific article. dr.ef.tymac 14:15, 20 July 2007 (UTC)
Right, what Dreftymac said.
I suggest tracking down a set of (reliable) sources, and drafting a new article based on them (with an eye toward reporting, not original research or instruction). —Piet Delport 11:33, 20 July 2007 (UTC)
- Makes sense, one problem though; there are plenty of published works that use this term, but how many of those are actually authoritative (and not just reflective of the same sort of "conceptual acrobatics" presented in this article)? It looks like everybody and his dog has some kind of clever variation on what this specific term actually means ... therefore rendering it meaningless.
- More and more, this article is looking like an excellent candidate for the bit bucket. Perhaps then the passage of time will permit something better to emerge from the ashes. dr.ef.tymac 14:15, 20 July 2007 (UTC)
- Wikipedia sources just need to be reliable: this excludes everybody and his dog's variation, so that's not a problem.
- Given that, i don't there's significant disagreement over what the term means. (Whatever there is should simply be summarized without bias, as per Neutral point of view.) —Piet Delport 04:16, 24 July 2007 (UTC)
- I'm in 100% agreement with you, Piet Delport, at least in principle. There are some practical considerations however, based on how this article has evolved, that are a tad troubling. Nevertheless, I don't want to be a naysayer ... things can always turn around for the better. dr.ef.tymac 11:29, 24 July 2007 (UTC)
I've just submitted a re-write of the intro. I haven't changed the content substantially, just re-ordered and (hopefully) clarified the text. It's still based on the Martelli quote because that's 1. correct, 2. visible, 3. Python related (and Python's the main forum for the terms use, albeit incorrect). I've also moved the biological analogy up, because that's an analogy that does actually help to explain it.
I wouldn't support deletion of the article, because the term won't go away just because wp. refuses to talk about it.
So, have at it! 8-) Andy Dingley 15:59, 24 July 2007 (UTC)
- No, the term won't go away, but the article itself will if enough people support the view that it is not likely to be redeemed to a state that can be considered encyclopedic. That's not something I want to see, but ... c'mon ... you've read it. You yourself provided enough background info on this very talk page to explain why this term is a huge black eye to the face of logical consistency and encyclopedic value.
- The problem isn't that WP refuses to talk about it ... the problem is that, so far, everyone wants to talk about it, but the people talking about it don't seem to want to "share notes" with each other. Anyway, that's all from me for now as my complaining isn't helping and I don't have much time to help out on this article for now. Thanks, Andy, Piet, and others who've given it a shot. Best wishes in your efforts. dr.ef.tymac 16:56, 24 July 2007 (UTC)
I'm unhappy with the latest revison of the intro. It's reasonable as an anodyne introduction to a non-controversial term, but the problem with the phrase "duck typing" is that it means (by accepted use amongst coders) pretty much the opposite of what the apparent meaning would be from the quotation. This introduction does little to indicate and certainly doesn't highlight the term as being problematic. Andy Dingley 11:38, 20 August 2007 (UTC)
- Hi Andy, I changed the wording to better illustrate how the phrase does evoke the term. Unlike you, I struggle when people say the name has nothing to do with what is being described, and so tried to show how it applies admittedly from my Dynamic language background. A question: Do you have a mainly dynamic language background? --Paddy 16:37, 20 August 2007 (UTC)
Biological analogy
[edit]I note that an anon IP has deleted the biological analogy section, and without any discussion. Personally I found this section useful as it's a clear statement and a good analogy. Should it be reverted? Andy Dingley 11:33, 20 August 2007 (UTC)
As a birdwatcher, I suspect Messers Shakespeare and Thomas may have been punning on the tendancy of ducks to try crossbreeding with anything that looks even slightly duck-like.
If the result is viable, the female then lays an egg and a type has been created. If not, she throws an exception and there is no new type.
The net result is that you get very odd-looking waterbirds, and the best way to tell if they're ducks is to look for waddling and quacks. --Davecb (talk) 22:20, 23 March 2017 (UTC)
Duck typing in programming languages
[edit]I think no mention of a programming language should be made in the main article unless it is established within their languages community by, for example, Duck typing being positively mentioned, (not necessarily on a wiki), on the languages home site, or major articles by very prominent members of the community advocating Duck Typing for the language, (e.g. by mainstream language tutorial authors).
This would help keep the page focused.
I know of no Statically Typed/Manifestly Typed language where this is the case, so I would be likely to keep mentions of languages such as Perl/Python/Ruby.
If this affects your additions then please give examples of Duck Typings advocacy/standing within the languages community. --Paddy 05:35, 24 August 2007 (UTC)
Confusing template sentence->(no) Static vs Dynamic typing
[edit]Hi there, could you please explain this? I find it most confusing. Thanks.
This again has some of the advantages of Duck typing, but a Duck type only has to implement methods actually called, and a function written without knowledge of its future use with other types can usually be 'Duck typed' in a language supporting Duck typing, without further modification.
83.67.217.254 19:41, 26 August 2007 (UTC)
DuckDecoy Example
[edit]- Lets say your writing a world of ducks simulation and you are quite happy with:
class Duck(object):
'One Duck for our world '
def __init__(self):
self.inflight = False
def defecate(self):
print "Crap!"
def soundoff(self):
print "Quack"
def move(self):
import random
self.inflight = random.choice([True, False])
def duckworld(duck):
'Normal actions of Ducks in duckworld'
duck.move()
if duck.inflight:
duck.defecate()
else:
duck.soundoff()
print "\nNormal Ducks"
d = Duck()
for i in range(5):
duckworld(d)
- Later, you could simulate a duck decoy that is just a duck that does not fly. if it does not fly then it does not need a defecate method and you can write a new DuckDecoy class and pass it to the duckworld() simulator without having to edit the duckworld simulator function:
class DuckDecoy(object):
"New Duck Decoy never flys so won't crap on you."
def __init__(self):
self.inflight = False
def soundoff(self):
print "Quack"
def move(self):
'Always on ground'
self.inflight = False
print "\nDecoy Ducks"
dd = DuckDecoy()
for i in range(5):
duckworld(dd)
- If we were using templates then DuckDecoy would need a defecate method even though it will not be used in duckworld.
- Note too that no further edits to function duckworld were needed to support duck typing. --Paddy 22:06, 26 August 2007 (UTC)
Many thanks for the explanation. However I must admit that even after I read and understood the example, the sentence above required three reads to almost get there. Yes, I'm slow, but I think splitting the sentence in two and perhaps including an example would help.
- You are not necessarily slow. It was a long sentence that I have now broken down. --Paddy 05:58, 28 August 2007 (UTC)
I also do not understand the reason of your recent blanket revert of my edits and would appreciate if you could explain it here. I also find your edit comment most puzzling, as I don't intend to start any wars. (Do you?)
- The page needs to be kept focused on Duck typing. Static versus Dynamic typing as a subject can be both controversial and inflammatory. I think your mentioning of compile time versus run time checking can be removed without loss to the readers comprehension of Duck typing. --Paddy 05:58, 28 August 2007 (UTC)
I think we want to make two points: 1. duck typing allows what you have described above, but 2. it comes at a cost, which is trading compile-time errors for runtime errors. Is that not the case? Thanks. 83.67.217.254 19:38, 27 August 2007 (UTC)
- Your item 2 above is Static vs Dynamic typing. Fight that war elsewhere. --Paddy 05:58, 28 August 2007 (UTC)
Also, I would like to point out that although it illustrates the point, the code in your example lacks of a sound design, as it breaks encapsulation. If a programmer comes about and decides that duckworld is not a good model because ducks sometimes defecate even when they are not flying, s/he is not going to check all the classes the instances of which are passed to duckworld within the program. I'm not criticising your code, which you undoubtedly wrote in 1 minute to kindly explain the sentence. I'm saying this in support of my claim that (even in your example) duck typing means essentially trading flexibility for runtime safety.
- You are offering criticism of the code, but the code is out on a public forum. Given the context, I can take it.
- The code took more than a minute to write, even in Python. I tried carefully to write something to edify the open-minded reader and may have exceeded that task.
- On sound design: the example is less than a screen-full, and in your own words - 'illustrates the point'. It has served its purpose for at least one reader and makes me think it may do the same for others. --Paddy 05:58, 28 August 2007 (UTC)
Finally, what do you think about using lowercase "duck typing" instead of "Duck Typing" throughout the article? Thanks. 83.67.217.254 19:54, 27 August 2007 (UTC)
- Lowercase is good. I checked on Dynamic_typing and they do it there. --Paddy 05:58, 28 August 2007 (UTC)
Oops, crossed in the post. 83.67.217.254 06:15, 28 August 2007 (UTC)
You reverted my change again without engaging in a conversation in this talk page. This is not constructive. I have changed more than one thing with that edit. Please explain the reasons why you want to revert each aspect of the edit.
You seem to be very keen on highlighting the most obscure upside of duck typing, but revert a fundamental downside, namely that the flexibility you get is traded for more runtime errors, as I explained above. With no mention of this trade-off, the article is biased and is a disservice to the reader. 83.67.217.254 06:11, 28 August 2007 (UTC)
In the article generic programming, templates are referred to as static duck typing. I think that is a good way of putting it. Static vs dynamic may be inflammatory, but I have no intention to start a war, I simply want the reader to be aware of pros and cons. Duck typing is inherently a static vs dynamic trade-off, so it would be a disservice to the reader if we didn't mention it. 83.67.217.254 06:23, 28 August 2007 (UTC)
- This article is about Duck typing. What may be obscure on an article that is not primarily about Duck typing may be essential in an article about Duck typing when it is a part of what distinguishes Duck typing.
- Again, I must emphasize that there are a great many programmers who favour the dynamic side of any 'static vs dynamic' trade-off for a large part of their programming needs, and that this is not the subject of the article. To widen the scope would lead to an unmaintainable mess - yet again.
- The article may not show your bias; but I think this is a good thing. I know of no language that has both templates and Duck typing abilities integrated to a similar degree, thus comparisons tend to be static vs dynamic typing as a whole. Take it elsewhere.
- What does 'static Duck typing' mean? If it means that Generic programming is the closest that most static languages can come to Duck typing then they may have a point, but I am wary of saying such in the main article. --Paddy 08:40, 28 August 2007 (UTC)
- And yes, I've reverted your changes. The reason remains essentially the same. --Paddy 08:40, 28 August 2007 (UTC)
I think I'm not the one showing bias here. As I see it, we are not here do decide whether duck typing is always good or always bad. We are here to report the advantages and disadvantages of this language feature. Deliberately hiding that there is a static vs dynamic trade-off involved is a disservice to readers, as well as biased, especially when comparing it to templates. Please stop reverting my changes. I have removed the reference to "static duck typing", although it is mentioned in the generic programming article and with a good reason. 205.228.74.13 09:29, 28 August 2007 (UTC)
- You wish to state that static is superior to dynamic typing schemes. I don't want you to state it here. Or discuss the falsehood or otherwise of it here. (I presume 205.228.74.13 is 83.67.217.254 but please get a name other than your IP address to avoid confusion) --Paddy 09:42, 28 August 2007 (UTC)
You are mistaken. I do not want to state the superiority of anything to anything else. On the contrary, you seem to be biased in your wanting to highlight only the positive aspects (flexibility) of duck typing and hide the negative ones. This is also supported by your unsolicited apology to dynamic typing claiming that "great many programmers" prefer dynamic typing, which is irrelevant here. As I have stated right from the start, I have no intention to start any wars, and indeed I can see only one person revert-warring here.
May I add that programmers stating that they prefer this feature to that feature (or even worse this language to that language) in absolute terms are not showing a great deal of experience. —Preceding unsigned comment added by 205.228.73.13 (talk) 10:00, August 28, 2007 (UTC)
You are correct in assuming that the two IP addresses are related to the same user, myself. My IP address is dynamic (see, no bias) and I have no intention to register. 205.228.73.12 09:51, 28 August 2007 (UTC)
Your reformulation still sounds quite biased to me. It sounds a bit like, "You may hear of templates as a way to imitate duck typing in static languages [by the way, what do you mean by "static language"? C++ and Objective-C have plenty of dynamic features], but they are really poor imitations because they are not as flexible as the real thing. Oh, and by the way, duck type checking is performed at run-time, whereas templates are static, whatever, that's not a big deal." The last sentence in particular is basically a euphemism for "templates may fail to compile, whereas duck types increase your program's exposure to run-time errors", which is in my view the main point when comparing duck typing with static language features like templates. This trade-off is being deliberately hidden. 205.228.74.12 10:26, 28 August 2007 (UTC)
I've changed the last sentence, making it clear that there is a trade off involved. 205.228.73.11 10:43, 28 August 2007 (UTC)
- If you reread my edit you will see that I do not mention static vs dynamic, but carefully chose what I would think would be the less emotive terms of compile time and run time without stating a preference. It does not require your edit.
- --Paddy 10:59, 28 August 2007 (UTC)
While I am glad you changed your mind about "I think your mentioning of compile time versus run time checking can be removed without loss to the readers comprehension of Duck typing.", your version is still biased in that it's very keen to portray duck typing as "more flexible" without stating that there is a downside, which there is. You are not addressing my concern that a language design trade off is being deliberately hidden.
Please stop reverting. I have conceded your (still biased) version, provided we explicitly mention the trade-off. Also I don't get this recurring theme whereby objectively mentioning the drawbacks of a language feature is "inflammatory", and static and dynamic are "emotive" terms, since they are basically synonyms of compile-time and run-time, respectively, which you now say you are happy to use. 205.228.73.13 11:24, 28 August 2007 (UTC)
- What proof do you have that the use of duck typing compared to templates is inherently error prone? You have given none. Let the text remain neutral. --Paddy 11:40, 28 August 2007 (UTC)
Please stop reverting. You are misconstruing my edit, which says that, compared to template-like features, duck typing increases the program's exposure to run-time errors. This is a self-evident consequence of the fact that duck typing checks types dynamically as opposed to statically. 205.228.74.12 11:47, 28 August 2007 (UTC)
- This is a ckear case were your intuition is wrong. hence the removal. You have added no further proof so leave it neutral. P.S. To whome am I addressing this? A dynamic IP address gives you a shifting identity. Try signing your entry in some consistent way. --Paddy 12:02, 28 August 2007 (UTC)
It's not intuition, it's logic. In a completely unreferenced article I don't see the need to reference a logical conclusion only because it highlights a drawback of a language feature that you are trying to portray as superior to templates in absolute terms (and interestingly accusing me of doing the opposite, while this is not the case). The existence of a language design trade-off needs to be stated in clear terms. There is nothing non-neutral about stating merits and shortcomings when comparing two language features. On the other hand, magnifying the merits and downplaying or not mentioning the drawbacks is not balanced. 205.228.73.11 12:17, 28 August 2007 (UTC)
- You still say that template types are less error prone than duck types without proof. If it is indeed logical then show the logic and it would stand. The need to code methods that are not used, and edit functions to accept templates, are extra changes and extra code that is minimized when duck typing, and are more likely to create errors in templating no matter where they are checked. Less code (added & modified), makes for less chance for bugs to be introduced. Where is your logic?
- Even so, I would not add that duck typing may be less error-pprone than templating to the main article, as it brings up the static vs dynamic typing issues that you introduced and fail to acknowledge introducing (repeatedly). :--Paddy 12:46, 28 August 2007 (UTC)
Number of run-time checks with templates-style generic types = 0. Number of run-time time checks with duck types > 0. It follows that, ceteris paribus, the number of potential run-time errors (as opposed to the compile-time errors that you mention in you latest comment) is strictly greater with duck types. Please let me know where we disagree. 205.228.73.12 13:01, 28 August 2007 (UTC)
- If one assumes the number of run time errors for a templated program >0 then it follows from your argument that they will not be checked. - This argument is what I wished to avoid, but you continue to prolong. The false edit will be removed. --Paddy 13:26, 28 August 2007 (UTC)
- Checks for template programs and interpreted programs are essentially the same, but with templates checks are made at compile-time rather than in runtime, thus certain kind of errors may be caught earlier. 89.189.179.81 (talk) 01:17, 25 January 2010 (UTC)
- Your point is made, after great deliberation, moderation, and in a better way, here. --Paddy (talk) 04:22, 25 January 2010 (UTC)
We will have to find an agreement first, I'm afraid.
"it follows from your argument that they will not be checked." Sorry, I don't understand. What will not be checked? 205.228.74.13 13:45, 28 August 2007 (UTC)
I notice that you keep reverting without attempting to discuss this any further. That's a pity, because I thought we were getting somewhere. 205.228.73.12 15:17, 28 August 2007 (UTC)
- You refuse to moderate or in any way change your unsubstantiated edit, or give adequate reason for its inclusion. --Paddy 15:39, 28 August 2007 (UTC)
Not true. I repeat: "it follows from your argument that they will not be checked." Sorry, I don't understand. What will not be checked? Thanks. 205.228.74.11 15:44, 28 August 2007 (UTC)
Requesting a third-opinion
[edit]- I've requested the opinion of a third party Wikipedia:Third_opinion#Active_disagreements. —Preceding unsigned comment added by Paddy3118 (talk • contribs) 16:05, August 28, 2007 (UTC)
This sounds like a good idea, thanks. 205.228.73.11 16:10, 28 August 2007 (UTC)
Not the WP:3O answer: This is not in response to the WP:3O request, but I've been somewhat following this article, and I notice there still is no foundation of reliable sources upon which to base either this discussion thread, or the article itself. This is a serious deficiency, and was the original reason why I suggested this article has serious problems. This flare-up seems like proof-positive of the fact. dr.ef.tymac 16:36, 28 August 2007 (UTC)
My opinion: First of all, both of you need to go read WP:3RR. I also second the call for sources to be added to this article. As far as templates versus duck typing, it appears to me that they are the same technique applied to static versus dynamic type checking. I would rewrite the section in question something like this:
Template functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic typing in general. Duck typing can also be more flexible in that only the methods actually called at run time need to be implemented, while templates require implementation of all methods that cannot be proven unreachable at compile time. Examples include the language C++ with templates, and the type(less) id of Objective-C.
This has a clear referral to the discussion of static versus dynamic typing for the advantages and disadvantages of what are basically very similar techniques. Anomie 17:05, 28 August 2007 (UTC)
I'm fine with that, thanks. 205.228.73.11 17:28, 28 August 2007 (UTC)
I have made the above edit and will read WP:3RR. --Paddy 17:48, 28 August 2007 (UTC)
External Reference request for some languages
[edit]It would be good if all the languages mentioned in the implementations sections had at least one reference given to its implementation of duck typing. That means references are needed for Coldfusion, Smalltalk, and Objective-C. --Paddy 17:19, 9 October 2007 (UTC)
C#
[edit]"While duck typing is used to implement the foreach statement" That is just plain wrong, foreach is done by the object implementing a particular interface -- this is not duck typing but strict inheritance. I suggest it is deleted. In addition anonymous types and duck typing are completely different. In the duck analogy anonymous types are a bit like saying 'I would like to be one of those quacky things over there' rather than actually being a duck :) RobChafer 09:56, 14 November 2007 (UTC) (signed in this time)
It appers that it has been deleted but I'm not sure if this is right since this blog [1] tells that foreach is NOT using a particular interface, the object just need to have:
A a public method GetEnumerator that takes no parameters and returns a type that has two members:
a) a method MoveMext that takes no parameters and return a Boolean, and b) a property Current with a getter that returns an Object.
BUT is it actully the object that needs to have those things? To me it appers that it is the class that the in-variable belongs to needs to have them since type checking ALSO is done at compile time. CAN THAT BE CALLED DUCK TYPING? (I'm new to all this so I don't know) Ulf L 192.71.76.2 (talk) 17:07, 17 November 2007 (UTC)
- I've asked on the blog if it might be structural typing. But even if it is. How much is it part of the language? When would it be part of a normal C# release? --Paddy (talk) 18:40, 17 November 2007 (UTC)
If you read the C# language specification (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf; what a concept, read the spec!), you will see that foreach will indeed use a properly declared GetEnumerator method, even if the type does not implement IEnumerable; and in fact, a public GetEnumerator method will supercede an explicitly implemented IEnumerable.GetEnumerator (though I can't understand why it was done this way). This is indeed an example of duck typing, the only one that I know of in C# prior to version 3.0 (e.g. LINQ, collection initializers). The original statement should be restored, and Mr. RobChafer should issue an apology :) Commongenius (talk) 19:24, 13 December 2007 (UTC)
- Is it confined to foreach or can the programmer use Duck typing in his own functions? Could you write the Duck&Trance or DuckDecoy examples above for example? (P.S. I am not a C# programmer so I'm asking directed questions for those who are). --Paddy (talk) 21:45, 13 December 2007 (UTC)
- It is confined to foreach, and to some of the new language features in C# 3.0. The programmer cannot use duck typing in his own functions. C# is still mostly a statically typed language; the only exceptions are those allowed specifically by the spec and implemented by the compiler. So you could not write the DuckDecoy above; any object passed in to the duckworld method would have to have a defecate member method, even if it would never be called. Commongenius (talk) 15:20, 26 December 2007 (UTC)
Duck Typing in relation to Reflection
[edit]What about Reflection in C#? is this duck typing?
public class Duck {
public void Quack();
public void Swim();
}
public class DuckRobot {
public void Quack();
public Weapon LaserGun;
}
object[] Array = new object[] { new Duck(), new DuckRobot() };
foreach(object quacker in Array) {
quacker.GetType().FindMethod("Quack").Invoke(quacker, null);
}
So, could a C# expert state what are the limitations of that languages dynamic capabilities that stops it from copying the Duck&Trance or DuckDecoy examples but seemingly allows the reflection above? Is it that the reflection is tied to array accesses? --Paddy (talk) 20:03, 28 February 2008 (UTC)
- I originally posed the example above, because I'm not sure what the distinction is. Regarding capabilities of reflection, there is no reason the duckdecoy and trance examples cannot be done in C# or VB.NET or possibly Java (IIRC, the Java runtime also has reflection). I would say that unlike duck typing, reflection isn't a language feature, rather it's an ability of the .NET runtime (as implemented in the System.Type and System.Reflection.MethodInfo classes) so perhaps the distinction is a semantic one. Talyian (talk) 23:12, 18 March 2008 (UTC)
Indeed, any language that has reflection could be used to implement a method that would work on 'any object implementing the Quack() method'. I'm not sure how to determine whether this would qualify as 'Duck Typing' though, as the definition is not that clear --Raboof (talk) 11:34, 24 March 2008 (UTC)
Static Duck Typing
[edit]Is the term 'duck typing' reserved for dynamically typed languages? I could well imagine a Java-like language that would allow the following:
interface Duck {
Quack();
Walk();
}
class RoboDuck /** does not explicitly implement 'duck'! */ {
Quack() { ... }
Walk() { ... }
}
performQuack(Duck duck) {
duck.Quack();
}
performQuack(new RoboDuck());
The language here does not check whether the parameter passed to 'performQuack' explicitly implements the Duck interface, but statically verifies that it does meet all the requirements of that interface. Definitely sounds like a 'duck check' to me - perhaps even more convincingly than the classic python/ruby example, as those do not make the 'then it's a duck' part explicit. --Raboof (talk) 11:34, 24 March 2008 (UTC)
- What I had in mind is called Structural typing (in contrast to Nominative typing), which gives some of the advantages of Duck typing, but is generally applied to statically typechecked languages. I wonder if you could say Duck typing is a form of Structural typing. --Raboof (talk) 14:29, 7 October 2008 (UTC)
Criticism
[edit]Currently the paragraph about criticism contains: "One issue with duck typing is that it forces the programmer to have a much wider understanding of the code he or she is working with at any given time." But that is totally wrong. In ruby you usually see .is_a? String or even better a .responds_to? some_method relationship. At this point you do NOT AT ALL need to understand WHAT the code is doing as long as it gives you meaningful results (which it should, since it will support "duck typing" already. Whoever wrote this was either biased, didnt know what he is writing about, or simply lies. It should be reworded or removed, because the issue as described here does NOT exist. Duck typing really is about not worrying at all that the object will do something "illegal" and it frees programmer's brain. —Preceding unsigned comment added by 80.108.103.172 (talk) 23:19, 17 April 2008 (UTC)
- sorry, you are promoting and arguing in favour, while this paragraph is about Criticism. In such an paragraph, it is not the point to show if the Criticism is true or false, it's about mentioning that there is Criticism. Much of the problem with this page stems from people trying to argue here (in the enceclopedia), instead of documenting (underpinned with valid references) the arguments brought forth elsewhere by the experts of the matter. —Preceding unsigned comment added by 91.12.1.109 (talk) 01:40, 22 July 2009 (UTC)
Another criticism of duck-typing is that it depends on testing, which in most software organizations can fall anywhere between 'ok' and 'terrible'. Compiler type checking is meant to catch a range of errors concerned with sloppy code organization and type usage. Duck typing assumes that away under the aegis of 'good testing', which is by no means guaranteed in most normal organizations. All software development methods depend on one thing not normally present in most programmers: discipline. In a situation where there are a lot of software engineers who exhibit discipline, duck-typed languages will most likely provide benefits. In more typical situations, things may not go so well (since many errors are delayed to runtime, which will inevitably be released to the field). I also agree with the above comments about 'presenting true or false'.. that is not the purpose of an encyclopedia. —Preceding unsigned comment added by 207.67.226.96 (talk) 01:26, 7 April 2010 (UTC)
Can I ask -- how would that criticism not be true with duck typing? Clearly the developer does need to know at least the following:
- That the method should exist (since it may or may not actually be written down or have docs anywhere).
- That the receiver on which the method is being called should be able to receive the method.
- What parameters the method should expect to receive (as well as some semblance of their types).
- What the contents and type of result will be returned by the method.
In languages that use static interfaces rather than duck-typing, the developer only needs to follow the documented contract, rather than having to have the knowledge & understanding for the above. If they aren't passing the right things or the method doesn't exist, they get immediate feedback in the form of a compile error. Granted, they may need to look-up more information to understand how to assemble everything in the static interface contract, but there's not a lot of knowledge the developer needs to already have to know what the signature of the method is. GuyPaddock (talk) 16:13, 31 August 2017 (UTC)
.NET not a language
[edit].NET is not a language, and if the dynamic languages under .NET do not support generics then the edit adding .NET to the languages supporting generics is wrong. --Paddy (talk) 08:49, 22 June 2008 (UTC)
Visual Basic
[edit]I've been playing about with VB for a bit, and it looks to me like this code supports duck typing
Option Explicit Off
Module Module1
Sub Main()
Dim donald = New Duck
Dim john = New Person
donald.quack()
john.quack()
donald.feathers()
john.feathers()
For JJ = 0 To 4
DuckWorld(donald)
Next
For JJ = 0 To 4
DuckWorld(john)
Next
End Sub
Private Sub DuckWorld(ByVal duck)
If duck.inFlight Then
duck.defecate()
Else
duck.quack()
End If
End Sub
End Module
Class Duck
Shared rand
Public Sub quack()
Console.Out.WriteLine("Quaaaaaack !")
End Sub
Public Sub feathers()
Console.Out.WriteLine("The duck has white and gray feathers.")
End Sub
Public Function inFlight()
If rand Is Nothing Then
rand = New Random
End If
Dim check = rand.Next(0, 2)
If check = 1 Then
Return True
End If
Return False
End Function
Public Sub defecate()
Console.Out.WriteLine("Crap")
End Sub
End Class
Public Class Person
Public Sub quack()
Console.Out.WriteLine("The person imitates a duck.")
End Sub
Public Sub feathers()
Console.Out.WriteLine("The person takes a feather from the ground and shows it.")
End Sub
Public Function inFlight()
Return False
End Function
End Class
It looks to me like VB9, at least, is pretty happy to duck-type, and can pretty much implement the DuckDecoy example shown earlier in the discussion. I believe this is backed up by section 1.11 of the MS document "visual basic 9.0 overview" which I found at http://download.microsoft.com/download/5/8/4/5841bc1a-e864-4423-bb75-d4f3c18c0af5/visual%20basic%209.0%20overview.doc I'm not going to make the edit myself immediately, because I'm a big ol' coward, but I might put it in in a couple of days if there are no objections here. Sorry for the lack of knowing what I'm doing, but I don't know what I'm doing. —Preceding unsigned comment added by 217.206.32.3 (talk) 10:15, 26 September 2008 (UTC)
EAFP for duck typing
[edit]For the case of Python, the article mentions that EAFP should be applied, but that can be very dangerous:
class Mallard:
def quack(self):
print self.missing_attr
m = Mallard()
try:
m.quack()
except AttributeError:
print "Mallard can't quack()"
Here the mallard can quack like a duck, but instead there's a subtle error in the quack method itself that is completely hidden by EAFP. It seems to me that catching any AttributeError when invoking a method like this is very dangerous. Is this really a best practice? --Krokicki (talk) 17:25, 30 June 2008 (UTC)
- I'll start you off with one article defending Duck Typing in Python and EAFP, that leads to others. Whilst no panacea, Duck Typing, and EAFP can and does work well. It's part of the dynamism of dynamic languages that may be un-intuitive to someone from a static language background.
- Oh, and the link. --Paddy (talk) 18:47, 30 June 2008 (UTC)
- Thanks for the link. I wouldn't say I have necessarily a "static language background" (learned C/Perl around the same time then C++/Lisp/Javascript and finally settled on Java/Python) but this blog article seems like complete rubbish to me. I guess it's because I do work with APIs that "others" end up using, and they're never as imaginary as this author suggests. Anyway, I didn't see anything there that addressed my specific question. I do "get" duck typing, and even EAFP in certain cases (casting text to ints is a great example). What I don't understand, is burying an entire class of exceptions to handle one special case of EAFP (as in the code above). Is there something I'm missing? Like if you could check how many levels the exception propagated through, and only print "Mallard can't quack()" if that AttributeError actually occurred on the quake attribute, then it would be fine. --Krokicki (talk) 20:02, 9 July 2008 (UTC)
DT in TCL
[edit]I think the link between "everything is a string" and "Tcl supports Duck Typing" should be deleted if it cannot be succinctly and relevantly explained for those who do not have much or any TCL experience. On reading the Wikipedia entry on TCL Arrays it states that arrays cannot be treated as strings, The TCL wiki also says similar the quote is:
- "It's also important to know that arrays have no implicit string representation other than their name".
Well, since everything is not a string, the phrase should be deleted. --Paddy (talk) 01:21, 8 July 2008 (UTC)
What The Duck!?!?
[edit]This article just doesn't make sense. That duck analogy is way too overused in this article. One should try to explain it in more normal terms before going to analogy.83.97.100.162 (talk) 12:00, 30 January 2009 (UTC)
- Could you expound on your problem please? --Paddy (talk) 17:06, 30 January 2009 (UTC)
- I think they're referring to this paragraph:
- In duck typing one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. It is this action of any object having the correct walk and quack methods being accepted by the function that evokes the quotation and hence the name of this form of typing.
- There's no particular reason this example uses a type called Duck and methods called walk and quack, other than for the sake of the duck analogy. Perhaps the original poster is asserting that a more practical example would be more illuminating. Dcoetzee 02:59, 31 January 2009 (UTC)
agreed. it tries to be way too cute (e.g. with the Person example) and as a result is much less clear. 70.225.162.174 (talk) 08:31, 10 March 2009 (UTC)
- I agree.
in_the_forest
doesn't make much sense either. 86.131.89.40 (talk) 21:49, 26 March 2009 (UTC)
- DISAGREE. I thought that the Python "quacker" was pure aesthetic, and pedagogic, brilliance! You guys just ain't got no sense of poetry! Made perfect sense to an old guy like me and when I was at school the only object-oriented and dynamically-typed language around then was Smalltalk! I came into the discussion with the intention of entering a thank you section note (for the above and for almost making me laugh with pleasure at it) until I saw you guys already croaking about applying a "monkey patch" to it! TUT TUT!! 120.156.76.77 (talk) 16:48, 9 January 2010 (UTC)
- The aim was to both explain duck typing and the choice of the name in an example that followed the spirit of the original quote whilst not being dry. I learn best when it doesn't seem like I am being taught because I am also being entertained. I don't think that the examples quoted should be changed. --Paddy (talk) 23:31, 9 January 2010 (UTC)
Oft cited
[edit]It is good English. --Paddy (talk) 17:05, 15 July 2009 (UTC)
C# implementation.
[edit]C# now has "dynamic member lookup" (See C_Sharp_(programming_language)#Dynamic_member_lookup), which I think should be added to this article in the Implementations section. (I don't know if other .NET languages such as VB.NET also support this.) I have not used C# or .NET for a long while, so someone else may be able to give a better treatment of it than me. For now, I'll just ad d a link to that article. SimonTrew (talk) 09:34, 17 July 2009 (UTC)
I have added a C# example to the article. I have also made an example using classic static types and interfaces, but did not see it as relevant enough to add to the main article, but I'll add it here for reference. Håvard Fjær (talk) 08:54, 19 January 2010 (UTC)
C# Duck typing
[edit]namespace DuckTyping
{
using System;
public class Duck
{
public void Quack()
{
Console.WriteLine("Quaaaaaack!");
}
public void Feathers()
{
Console.WriteLine("The duck has white and gray feathers.");
}
}
public class Person
{
public void Quack()
{
Console.WriteLine("The person imitates a duck.");
}
public void Feathers()
{
Console.WriteLine("The person takes a feather from the ground and shows it.");
}
}
internal class Program
{
private static void InTheForest(dynamic duck)
{
duck.Quack();
duck.Feathers();
}
private static void Game()
{
dynamic duck = new Duck();
dynamic person = new Person();
InTheForest(duck);
InTheForest(person);
}
private static void Main()
{
Game();
}
}
}
C# Static typing
[edit]namespace StaticTyping
{
using System;
public interface IDuck
{
void Quack();
void Feathers();
}
public class Duck : IDuck
{
public void Quack()
{
Console.WriteLine("Quaaaaaack!");
}
public void Feathers()
{
Console.WriteLine("The duck has white and gray feathers.");
}
}
public class Person : IDuck
{
public void Quack()
{
Console.WriteLine("The person imitates a duck.");
}
public void Feathers()
{
Console.WriteLine("The person takes a feather from the ground and shows it.");
}
}
internal class Program
{
private static void InTheForest(IDuck duck)
{
duck.Quack();
duck.Feathers();
}
private static void Game()
{
IDuck duck = new Duck();
IDuck person = new Person();
InTheForest(duck);
InTheForest(person);
}
private static void Main()
{
Game();
}
}
}
C++ and D template example removed
[edit]Mainly because it was an example of templates rather than duck typing and did not, for example, succinctly give any more comparison info on templates vs duck typing except by wading through a template example. --Paddy (talk) 15:26, 24 January 2010 (UTC)
- Templates apply a duck test at compile-time. Also, the article now suggests that Java generics and C++ templates are similar. This is wrong, because they are fundamentally different in underlying mechanism and abilities, sharing only < > brackets. Generics use interfaces which need to be declared explicitly, and templates are independent of OOP. 89.189.179.81 (talk) 00:30, 25 January 2010 (UTC)
If you reread the original you will see that the full paragraph notes a similarity between Java generics and C++ templates in the context of them both requiring implementation of all methods that cannot be proven unreachable at compile time. Two languages features can both share an attribute without them being the same. Unless you have evidence that refutes the original I will reinstate it. --Paddy (talk) 04:48, 25 January 2010 (UTC) It's not generics what requires implementation of methods, that's interfaces. C++ has neither generics nor interfaces. Here is the evidence. This code compiles without warnings and fails at runtime. You *CANNOT* get same behaviour with template classes. In C++ STL, one gets ugly long compilation errors instead.
import java.util.*;
class foo {
public byte x;
}
public class TreeS {
public static void main(String[] args) {
TreeSet<foo> t = new TreeSet<foo> (); /* Instantiate generic container */
foo f = new foo();
t.add(f); /* completes successfully */
System.out.println("It's ok");
t.add(f); /* produces error:
Exception in thread "main" java.lang.ClassCastException: foo cannot be cast to java.lang.Comparable
*/
}
}
There is nothing common with C++ and Java besides C heritage and hence curly brackets and static typing. Only superficial similarity. —Preceding unsigned comment added by 89.189.179.81 (talk) 14:20, 25 January 2010 (UTC)
- also, the statement Duck typing can also be more flexible in that only the methods actually called at run time need to be implemented, while templates require implementation of all methods that cannot be proven unreachable at compile time. is of low value because in the programmer can always statically add empty method which throws exception and get the same run-time behaviour as with interpreted languages. 89.189.179.81 (talk) 00:37, 25 January 2010 (UTC)
Instead of aggressively promoting POV by reverting edits, could you please supply Java analogue for code in Python? 89.189.179.81 (talk) 00:41, 25 January 2010 (UTC) Here's an example where templates are safe form of duck typing. In C++ there is std::set container template which implements set using balanced trees where values are compared (by default) using operator<. Given a class foo, one can declare variable of type set<foo> and it will compile and run even if no operator< is defined for type foo. If one tries to insert a value into set and foo does not have operator< defined, program will not compile so no run-time checks are needed, in fact, is it even not possible to do them. Another example, you can declare empty variable with type vector<int[2]> and program will run, but trying to insert values into vector<int[2]> will fail at compile-time, because it is wrong type. Also, difference with Java. In C++, if one has to use type foo in set container, one defines foo using
class foo {
/* member vars */
};
bool operator < (const foo &a, const foo &b) { // OUTSIDE CLASS DEFINITION
return /*...*/ ;
}
In Java, to use foo in TreeSet (which corresponds to C++ set container), one defines foo using
class foo implements Comparable<foo> {
/* member vars */
public int compareTo(foo other) { /*...*/ }
}
They share nothing except curly brackets. —Preceding unsigned comment added by 89.189.179.81 (talk) 01:12, 25 January 2010 (UTC)
SLIME
[edit]SLIME is not a REPL —Preceding unsigned comment added by 160.36.57.47 (talk) 00:29, 29 March 2011 (UTC)
Duck typing is a form of structural typing
[edit]To quote from Pierce (Chapter 19.3, page 252).
"Type systems like Java's, in which names [of types] are significant and subtyping is explicitly declared, are called 'nominal'. Type systems like most of the ones in this book in which names are inessential and subtyping is defined directly on the structure of the types, are called 'structural'."
Note that Pierce's definitions make no mention of static versus dynamic typing / type checking. My reading is that Duck typing is a dynamic form of structural typing, where the structure consists of the names + types of the exposed fields and methods. —Preceding unsigned comment added by 124.187.111.157 (talk) 05:43, 17 April 2011 (UTC)
- OK, the book author might know all about Java type systems, and maybe a something about others, but you don't quote from the book anything that mentions DT? Does the book state that DT is the same as ST? Are you therefore left to imply as the book doesn't state it? Could it be that the book has thrown out some general classification strategy without knowledge of all that it is trying to classify?
- Try getting a better source. --Paddy (talk) 02:29, 18 April 2011 (UTC)
Golang Section?
[edit]Should there be a section on Google's language, Golang, and its use of Interfaces to establish duck typing? (I personally do not understand Golang enough to author it myself). Gavintlgold (talk) 01:19, 13 June 2011 (UTC)
- Is it an interface or is it Duck-typing? If the former, then it should not be included. --Paddy (talk) 06:46, 13 June 2011 (UTC)
Not good enough
[edit]This page could be improved quite considerably. The examples make it less clear, especially as they use this playful but unhelpful duck example.
If I had to explain duck typing to someone, I would put it very simply as follows...
With static type systems, you specify the particular type that a value adheres to. In a language like Java, you might specify the type signature of a method as follows:
public static String randomlySelectMember(ArrayList<String> list) { /* ... */ }
In languages like Python and Ruby, you do not specify a type annotation for the arguments provided to the function or method:
def randomly_select_member(list)
# method body
end
In the Java example, you know by reading it–and the compiler knows when compiling it–what type of value should be passed as the argument to the method. But as no type is specified in the Ruby example, how does one know? Duck typing simply specifies that the type is enforced by you not being able to call certain methods or use certain functions on a particular value.
One could enforce the type by checking that it is of the relevant class using whatever facility the language provides:
def randomly_select_member(list)
if list.kind_of?(Array)
list.sort_by { rand }.first
else
raise ArgumentError.new("Array expected")
end
end
But the problem is that there are many classes of things which have the same methods as an Array does, specifically the ability to be sorted and for members of that array to be accessed. For someone writing a function, duck typing often means simply leaving off any type checking logic at all:
def randomly_select_member(list)
list.sort_by { rand }.first
end
The type is being enforced because if you pass a value that does not have the ability to "sort_by", it will raise an exception.
In the Java example, the type is enforced because the compiler checks to see if the type of the value that is passed to the method matches the type annotation. With duck typing, you simply rely on the fact that if something of the wrong type gets passed to a method or function, it will raise an error.
Any reasonably competent programmer should be able to read the above and understand the difference between static and duck typing. I'm not sure the same thing can be said of the existing text on Wikipedia, and we should really consider dramatically changing because currently it sucks.
p.s. If I had to explain it to someone learning Ruby, it could simply be boiled down to "Use responds_to? and not kind_of?!" —Tom Morris (talk) 11:57, 10 November 2011 (UTC)
- Your tirade boils down to "Put it in terms of Java please so I can understand", but without the please. You might have some small merit, but a Java-centric view of DT would be worse. --Paddy (talk) 18:56, 10 November 2011 (UTC)
- It's somewhat irksome that you see the feedback as a tirade: it was not meant as such.
- The description I've given above isn't "Java-centric". It simply boils down to this: to explain a type system, you can either talk in very general, academic terms, or you can use clear, specific examples. The latter tends to work better if the goal is to actually help people understand what you are talking about. And if you are going to use clear, specific examples (rather than vague, playful ones about ducks), it is best to not be intentionally obscure. I could have used Haskell or Erlang or Boo where I used Java, but that hardly helps people actually understand it. Chances are most people who are going to be reading about duck typing will have studied a mainstream object-oriented programming language without duck typing. What fits the bill? C, C++, Java, C#. Do I care which one? Not particularly. Does it make it better to have twelve different examples? No. If the thing hasn't been explained clearly at a conceptual level, giving examples in more languages doesn't make it clearer. I could tell you how to say "kidney" in twenty different natural languages, but being able to say that a kidney is a כליה and a bubreg doesn't help if you don't actually know what the organ does.
- What I do care about is the fact that numerous programmers I know have looked at this article and have said it is confusing, unhelpful and unclear and muddles up operator overloading and duck typing. That's all I was trying to do: put up an example of what I would consider a clear, straight-forward explanation intended for someone who doesn't know what duck typing is. —Tom Morris (talk) 13:56, 12 November 2011 (UTC)
- Hi Tom, The title you gave to this section, and I count now two revisions in which you have later retracted some incivilities in your comments did not hide the general tone.
- I wonder what is your, and your friends comments on the Comparison section?. You did mention C# above which has had some duck-typing ability added lately, would you care to maybe comment on any C# explanation of their Duck-typing ability - there maybe something there that would help refine this entry rather than advocating wholesale replacement by an article viewing Duck-typing solely by its relationship to Static typing.
- On the examples: Put one language exapmle in and everyone sees it as a slight on their language if theirs is not included. It is difficult to police.
- Could you also give more information on exactly where in the current article you think operator overloading is clouding duck typing? - Thanks, --Paddy (talk) 21:40, 13 November 2011 (UTC)
Spammy examples
[edit]The examples are very verbose. Perhaps someone could shorten them down to the minimum possible - and remove all the silly duck stuff. The Python example is a good, meaningful, succinct demonstration of the principle. Stevage 06:55, 30 November 2011 (UTC)
- Would it be possible to create a List of examples of duck typing page and move most examples there? If it is just pruned then there will be problems with the decision over why a particular language is removed. There should be much less argument over why languages are merely moved. (What is the process for creating such a list-of page)? --Paddy (talk) 13:17, 30 November 2011 (UTC)
- Why would we need such a page? What's it trying to achieve, and does it do so? "Lists of examples" are always risky, because they're attractive targets for editors to add to, because they want to add things more than there is a need for them to be added. There is no serious interest in a list of such examples for comparative purposes across languages (such a comparison needs to describe grammatical features. not list code fragments). The only useful purpose of giving such fragments is to explain duck typing as a principle. Anything else is padding.
- The examples should be placed where they're needed - where duck typing is being explained. The examples should be written to explain duck typing. They should cover multiple languages only as far as this is useful to highlight the duck issues and abstract them from specific languages. Anything else is paddding, and for the purpose of this article, harmful padding. I don't care if it's "interesting" to see duck typing expressed in Fortran, it has no useful contribution to this article, so it needs to go.
- If you think Comparative study of duck typing across programming languages stands up as a notable article, then go for it - but I can't see it myself. Andy Dingley (talk) 13:43, 30 November 2011 (UTC)
- My real point is that the examples are long - and full of lame duck jokes. You can demonstrate duck typing in 5-6 lines I think. Stevage 03:31, 2 December 2011 (UTC)
- I don't know why this discussion hasn't been properly carried on since 3 years, but this page seems more suitable for Rosetta Code than for Wikipedia IMHO. As was mentioned above, a couple of examples would be enough, rather than one per programming language. --DeathScythe00 (talk) 12:55, 14 October 2014 (UTC)
- My real point is that the examples are long - and full of lame duck jokes. You can demonstrate duck typing in 5-6 lines I think. Stevage 03:31, 2 December 2011 (UTC)
What is Duck Typing ?
[edit]Here is what I understood from this article?
- two or more classes may have methods which all have the same name.
- all of these (two or more) methods may return different types of data.
- all of these (two or more) methods may take different types of data as arguments.
What I don't understand is that do we need a special name for such a feature? AFAIK, all oop languages have that feature.
--129.7.147.112 (talk) 15:41, 15 December 2011 (UTC)
- That's not really the point at all.
- For starters, it's important to distinguish between method names and method signatures. A name is the name typed into the source. The signature is this name (or the implied identifier) together with the set of input and output parameters. In some languages, it's permitted to have multiple methods (as distinct methods) that are only identified by their signatures, i.e. you can re-use the same name with different parameters, and hang different sections of executable code onto these methods. This is not duck typing.
- Duck typing is more about the identity of objects, as compared to classes.
- In a simple single-inheritance, class-based language like Eiffel, then there is no room for duck typing. Objects are concrete instances of class definitions. Methods are bound to classes, thus bound to objects. Other objects, of different classes (and not sub/super classes), have entirely separate sets of methods that cannot be used interchangeably.
- With Turbo Pascal (1990-ish) there was often manually-done typecasting of objects. This allowed powerful polymorphism between branches of the class inheritance tree, but this was a scary process - it pretty much ignored the constraints of the defined language, so you were on your own when it came to checking the validity of method calls. Andy Dingley (talk) 10:45, 23 December 2011 (UTC)
- In Java, methods are often defined by interfaces rather than implementation classes. Objects still have a rigid definition from a single class, and that class defines the set of methods implemented. However interfaces can be shared between implementations, so duck typing is fairly easy. Just implement the
Quacking
interface and theWaddling
interface and you're done. Interfaces can define either one method or many, so you could even define and implement aDuck
interface that does the lot. - In Python or JavaScript, there is little in the way of class and far less in terms of interface. Objects are themselves first-class entities that may be manipulated dynamically during program execution. There might appear to be a "class", but this is really more of a prototype and is itself a dynamic entity, capable of manipulation. As there is less of a solid link back to an implementation class, these are the languages for which duck typing are most important. There is little or no useful way to ask "What class is this object?" and so we find ourselves instead looking for individual behaviours (i.e. methods) and seeing if they're available.
- Duck typing is a misnomer, and the concept is generally misleading. It's applied most closely in the original sense to languages like Java (with expressive, flexible interfaces) where the concept of "a set of conditions are met, therefore this is a duck" can be applied. Although the term is most commonly applied to Python, this is almost always used wrongly. Martelli's original Python quote was in contrast to duck typing, not as an example of it. Python is more like "quack typing": If something can quack, we can use it as a quacker, whether it's a duck or not.
- Andy Dingley (talk) 20:58, 15 December 2011 (UTC)
- Thank you for clarification Andy Dingley. Therefore, can we say:
- "Duck typing is; being able to instantiate objects (1) which are of different type, (2) and which all possess certain methods (3a) that have same method signatures (3b) but have different code."
- --76.31.238.174 (talk) 03:12, 23 December 2011 (UTC)
- As a trivial point, your (3b) should be stated as "may have different code". They can do (and it's most interesting when they do), but it's not part of the requirement. Two identical mallard ducks are still "broadly duck-like" by the test.
- "Duck typing" has two definitions, and both are in common use - hence the confusions.
- One is the "Is this like a duck?" test, and is pretty much as you describe. Your constraint (2) (if read as "must possess all certain methods") applies, they must implement the complete set to be considered "ducks". This is Java-like behaviour, where an interface not only defines the signature of methods, but also a set of methods.
- The other is the Python-like behaviour, where
Quack
andWaddle
methods are considered separately (i.e. your (2) doesn't apply). This isn't duck typing, per the original definitions, it's more flexible than that. You can't say "This object is a Duck" but you can say "This object is Duck-like for the sub-set of behaviours which are important to me in this particular context". Maybe you need toQuack
today, but not toWaddle
, so you just don't care ifWaddle
is supported or not. Now you might see this interpretation as "wrong" (I do, I think Martelli did), but this is the more common way in which it's interpreted today. - I never use the term "Duck typing" and I don't encourage others to use it, because it has these two contradictory interpretations. Andy Dingley (talk) 10:45, 23 December 2011 (UTC)
- Then, (x) the objects don't have to implement all methods and (y) the objects don't have to code those methods differently i.e. two objects may code the methods exactly the same. So the revised definition:
- "Duck typing is; being able to instantiate objects (1) which are of different type, (2) and which all may possess some or all of certain methods (3a) that have same method signatures (3b) but have same or different code."
- Explanation: There is a "method signature pool". All method signatures in the pool are accesible to all objects. Any object may select one, some or all of the method signatures from the pool and code them as its method. While coding, the methods of the same method signature doesn't have to have the exact same code. Objects may have different or same code in the related methods.--76.31.238.174 (talk) 02:01, 27 December 2011 (UTC)
- I think that if the technique of duck typing has any real value, it would be in the ability (not available for simple use of post facto implementing an interface) to implement only a subset of an interface's methods, where only a subset is needed or useful. This can be done (easily) in Python, although (as discussed) this is the "Quack typing" model and not the simple interpretation of the "Duck" model. Thus your (x) is key here.
- "same method signatures" should probably be "compatible method signatures". If signature allows a varying number of parameters, several formal declarations could be compatible with different actual calls.
- I don't understand your "method signature pool", at least not as a design concept. We might have such a thing as an implementation detail, when binding calls to methods, but at design time we think in terms of either objects (and then binding behaviours to them) or else behaviours (and then grouping these into objects). I can't think why an architect or software designer would be thinking primarily in terms of narrow method signatures (i.e. bundled parameters) at this time.
- Whatever duck typing is, I think we can all agree that it becomes a run-time mechanism for categorizing actual objects into "compatible" and "non-compatible", based on their implementation of particular methods and signatures. There is interpretation variation as to the criteria for compatibility, and also the time at which the type checking can be done could be brought forwards to compile or link time in some languages.
- As an aside for statically typed languages like Java, an obvious use of dynamic typing within their language's constraints would include any use of a Factory design pattern. Andy Dingley (talk) 13:53, 3 January 2012 (UTC)
- Much confusion above in trying to apply duck typing to Java. Java is not dynamic enough to exhibit the behaviour and if you start from the premise that it does then you are likely to end up in a mess. --Paddy (talk) 10:39, 30 December 2011 (UTC)
- Why does duck typing require a dynamic behaviour? - and for clarity, what do you mean here by "dynamic"?
- I would note though that the use of Java here is because it's well-known and supports a clear mechanism for bundled methods, not because it's dynamic or not (it obviously isn't). Andy Dingley (talk) 12:00, 30 December 2011 (UTC)
- Hi Andy, because in duck typing it's just what's there when a method is called that counts. If a method isn't called then it doesn't have to be there; if it's not there at definition it may be added any time before it is called. This distinguishes it from structural typing, (amongst others).
- I nearly forgot - by dynamic I mean a class whose attributes can be changed at run time. An example might be when you have a function that takes a file and amongst other things does a seek to the beginning of the file. You could call it with a zipped file that normally does not have a seek method, by adding a seek method that merely re-opens the zipped file. The seek functionality added is all that is necessary to allow your original function to now work with zipped files as well as normal files without any change to the function, (but a dynamic addition to that zipped files instance methods). --Paddy (talk) 18:36, 30 December 2011 (UTC)
- So I guess that I can describe your position as, "duck typing is only relevant if objects can change their behaviour dynamically."
- I would disagree with this - because of the difference between formal and actual parameters.
- Consider a statically-typed OO language. The objects themselves are profoundly static. Yet I would still claim that duck typing can apply here. The reason is that we often work, not with objects, but with objects passed as parameters. We don't know the type of these objects (we might know a parent class, which was used to declare the parameter type, but not their actual class). It's quite common to wish to pass in a variety of (related) objects through a parameter and these may thus offer a variey of methods. We can test the parameter object's type (or method set) and execute different methods as available, in typical Pythonic fashion.
- It is admittedly unusual behaviour for a statically-typed OO language to be used in this way. It usually involves some level of typecasting, with varying levels of relaxing the safety of static typing and compile-time checking - scary stuff to most static programmers. At its simplest (and still type-checked), is classic Meyer-style polymorphism: a parent class (probably abstract) is invented to be the parameter type, defining the set of methods possible. At the other extreme, typecasting is hammmered onto them and methods are applied optimistically according to some metadata-based guesswork. This is admittedly unusual in the Java world, it used to be a lot more common in the early days of Object Pascal, but it does happen and it shows how a parameterised object in a statically typed environment can still be of an unknown type at the time one comes to make use of it.
- Duck typing is of use when it controls the methods invoked in a context. There is a question (see my point above) as to whether the atomicity of duck typing is at the "duck" (set of methods) or "quack" (individual method) level. I doubt we'll ever see a clear agreement as to which. Whether it's restricted to dynamic languages though, I can't see this because even static languages can be used in ways that make them appear dynamic in minor, but sufficient, ways.
- Andy Dingley (talk) 21:00, 30 December 2011 (UTC)
- Andy Dingley, is my last def,niton correct according to your understanding?--76.31.238.174 (talk) 03:51, 1 January 2012 (UTC)
- Much confusion above in trying to apply duck typing to Java. Java is not dynamic enough to exhibit the behaviour and if you start from the premise that it does then you are likely to end up in a mess. --Paddy (talk) 10:39, 30 December 2011 (UTC)
Remove Dragon example in critisims
[edit]I think the dragon example in the criticisms section should be removed (or referenced if it is a quote). The reason being that in your class design you wouldn't put a quack method on a Dragon class, so duck typing doesn't even apply in this case. I think the existing example of Wine.press() vs Trousers.press() is adequate. Thoughts? Brindy666 (talk) 10:25, 20 January 2012 (UTC)
- Agreed - the section is a nonsense. The Trouser and Wine examples confuse subjects and objects, so they're just bad OO (Trousers are pressed by Corby trouser presses, they don't press themselves).
- The point of duck typing is that if Dragons can quack (and maybe swim), then they're thus welcome in the duck pond. Acceptability is based solely on this, we don't also judge by the side effects of their eat method being the consumption of other ducks, not just pondweed. Andy Dingley (talk) 11:21, 20 January 2012 (UTC)
Go example uses interfaces
[edit]This is a direct contradiction of the introductory paragraph, which says one can create the duck example WITHOUT using interfaces or inheritance.
modify intro OR drop example? — Preceding unsigned comment added by Ooskapenaar (talk • contribs) 14:29, 20 February 2012 (UTC)
- Go's "interfaces" are structurally-typed, which are different from the nominal interfaces used in Java, etc. Types do not have to explicitly conform to interfaces. Thus I can define an interface at any place and it will match existing types that have those methods. Thus I can use this as duck-typing: any time one needs to use a method on a value that is not know to support it, I simply do a type assertion to a dummy interface that I create with the desired method. Then I can use that method. That is basically duck typing.
- Perhaps it should be more clear that not all things called "interfaces" are the same thing. --208.80.119.68 (talk) 00:29, 25 May 2012 (UTC)
- I presume however that even if a method is unused in a function it must have that method to conform to the interface which is not necessary in DT. --Paddy (talk) 08:23, 25 May 2012 (UTC)
Article appears biased
[edit]After reading this talk section and experiencing seemingly random deletions by Paddy3118, I wish to call for a dispute resolution. It appears that Paddy3118 has a strongly formed opinion that there is no such thing as Duck-typing in static languages. While multiple authors here believe there well is. This needs to be documented and clearly worked out rather than just deleting our works on sight. I don't see any harm in stating that generic programming is seen by some (many?) as duck-typing - rather than suppressing this point. Unless there is some authoritative reference stating that Duck-typing is by definition connected to a dynamic type system, I would defend the position that generic programming is a perfectly valid way to implement the concept of Duck-typing. — Preceding unsigned comment added by Wiki Tesis (talk • contribs) 08:15, 29 October 2013 (UTC)
- Hi Tesis. Sections 3.1, 3.2 and 3.3 distinguish Duck typing from similar schemes. Does the method you propose fit any of them? I note that rather than try and argue why your example language should be included you seem to be stating that because you can accomplish one example that happens to not show a run time addition of class methods which is the dynamic part of DT, that that is enough for your examples inclusion.
- Duck typing is a term from the dynamic languages world. If not then it would be just another word for probably generic or structural typing and so redundant. So, does what you propose match any of the typing schemes that DT is compared to in section 3? What is the normal term used for what you propose in your languages documentation? Is your language statically typed? We could have a discussion. --Paddy (talk) 23:15, 29 October 2013 (UTC)
"Duck typing is a term from the dynamic languages world." - Even if this is historically true, it still does not mean that the typing-concept does not apply to static languages as well. A typing-concept as a language-independent concept is not defined by the fact in which language it appeared first, but by the underlying concept it represents. Section three states "Template, or generic functions or methods apply the duck test in a static typing context" - which I believe is correct to say. And while I believe that the Duck test is the essence of Duck-typing, you seem to believe that the fact that it is done at run-time is the defining feature. Nothing in the original references to Duck-typing seem to support that. Please provide proof to the opposite if my view is wrong. Duck-typing is also not redundant with respect to structural or generic typing as the concept can be interpreted as a specific case of e.g. generic typing, while it also applies to dynamic typing environments (without any generic elements). I would still stick to the interpretation that Duck-typing refers to the concept of dispatching based on the characteristics of the methods or functions which are defined on a type. Whether this is done statically of dynamically is a secondary feature. — Preceding unsigned comment added by Wiki Tesis (talk • contribs) 01:47, 30 October 2013 (UTC)
- I haven't seen duck typing discussed as a concept in static languages (perhaps it is though). It doesn't matter whether it is a concept, just whether it is discussed as a concept by secondary sources, not original research. Seems completely fine to me to add content about static languages, but it needs to be referenced, with noteworthy sources (not a non-expert blog post with 0 comments). In the current version I just saw, the only reference (other than a podcast about Boo that I didn't watch), was a StackOverflow post with 5 upvotes. Whereas it's extremely verifiable for Python. Anyway, I condensed the original research about reflection, etc. into a couple of sentences. dmyersturnbull ⇒ talk 21:14, 2 February 2022 (UTC)
Eric Lippert
[edit]Eric Lippert discussed the Wikipedia article on Duck typing today on his blog. The article and its comments may be useful for improving this article. Martijn Hoekstra (talk) 16:25, 3 January 2014 (UTC)
- And Phil Haack is weighing in too now. Martijn Hoekstra (talk) 12:18, 5 January 2014 (UTC)
- And code better too. Martijn Hoekstra (talk) 12:38, 5 January 2014 (UTC)
- And Haack again. Martijn Hoekstra (talk) 13:53, 7 January 2014 (UTC)
- And code better too. Martijn Hoekstra (talk) 12:38, 5 January 2014 (UTC)
Static Duck Typing
[edit]This seems to be a point of contention (see this question on Stack Overflow: Duck typing, must it be dynamic?). The article itself is contradictory - first stating that duck typing exists in static type languages, then contrasting it with the static-typed equivalents.
- Hi, it is not contradictory there. If you read the whole sentence it states only in "static" languages that have the ability to force type resolution at runtime. For those that don't, the comparisons are valid. --Paddy (talk) 13:46, 9 July 2014 (UTC)
Both positions seem to be coherent, but the opinion that patterns in static-typed languages that resemble duck typing count as duck typing seems to be more popular among those I've heard from so far. --Brilliand (talk) 16:39, 17 April 2014 (UTC)
An explicit statement that the term has no precise definition (as is with Strong and weak typing) may be appropriate. --Brilliand (talk) 16:48, 17 April 2014 (UTC)
Most examples missing "dog"
[edit]It was nice to see the "dog" example in the C++ code, showing how it won't even compile and thus is commented out. However, to my eyes, it seems that one of the major features of duck typing is to handle the "dog" case, yet the "dog" case and its results are missing from most of the examples (even the languages whose philosophy embraces duck typing). I want to know what happens in Python when "in_the_forest(Dog())" is called. Nothing? Is an error printed? Is an exception thrown? 216.64.156.5 (talk) 11:11, 6 October 2014 (UTC)
F# mention is wrong
[edit]I know very little about F# but I do know that it supports both dynamic duck typing and structural types. The desription of F# in the **In statically typed languages** section is simply wrong, since it claims F# checks at compile time, but also silly, since this article takes the position that Duck Typing is inherently dynamic and so F# should not be in that section if the claim about F# were accurate. As it is, the language should have a mention in both this section and **Structural Types**. If nobody else corrects this, I will once I have learned more about F#. Itsbruce (talk) 11:41, 14 January 2015 (UTC)
"style of typing" vs. "layer of rules on top of typing"
[edit]I had modified the article's introduction by replacing the previous "duck typing is a style of typing" with "duck typing is a layer of programming language and design rules on top of typing" and elaborated the discrimination with two pairs of sentences highlighting two key differences between ordinary typing and duck typing.
For this, the edit summary offered the explanation "Differentiate duck typing more clearly from type systems (which exist below duck typing in most languages)".
Paddy3118 reverted the modification without giving an explanation why. So let me now offer some further explanation for my modification: The previous version already referred to the article Type system. The Type system article states "a type system is a collection of rules that assign a property called a type to the various constructs".
Indeed, duck-typed languages do also have an ordinary type system in that sense. For instance in Python, the expression type(obj) will return the type of any object obj (so type("a") will give you the string type str). Duck-typing is obviously something in addition to that. It is this aspect of the confusion around the term duck typing that my edit addressed.
I will now undo Paddy's revert. Paddy3118, if you think my modification is inappropriate, please explain here on the talk page why and let's discuss this until we reach a consensus. LutzPrechelt (talk) 18:26, 9 April 2015 (UTC)
Wrong Result
[edit]The example "pseudo-code" is:
[edit]function calculate(a, b, c) => return (a + b)*c
example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)
print to_string example1
print to_string example2
print to_string example3
And the result as written is:
[edit]If translated to Ruby or Python, for example, the result of the code would be:
9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
apples and oranges, apples and oranges, apples and oranges,
But, the sum of [1,2,3] with [4,5,6] times 2, in my opinion is [10,14,18] and not [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]:
[edit](a+b) --> [1,2,3] + [4,5,6] = [5,7,9]
(a+b)*c --> [5,7,9] * 2 = [10,14,18]
Am I right?
[edit]I believe you are wrong. This is confusing, and if taken literally, the + and * of python are indeed supposed to concatenate. This is why, in my opinion, since duck uses the default implementation of the method, the example should show the concatenation and not the dot operations. — Preceding unsigned comment added by Nadavge (talk • contribs) 13:24, 22 January 2016 (UTC)
Most examples are not representative of duck typing
[edit]Most of the examples includes "Duck" and "Person" or something similar, but both types include the same set of methods.
This can lead a reader to wonder what's the difference between DT and structural typing.
The examples should outline more of the fact that an object could only implement a subset of the duck behavior (as Alex Martelli noted in his original post[1] "[...] check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need [...]"), which is one of the main difference with structural typing. As an example, this can be done with a "string action" argument which tells the received object what to do.
Geod24 (talk) 13:45, 23 November 2015 (UTC)
Determination of suitability
[edit]The article says:
"... suitability is determined by the presence of certain methods and properties (with appropriate meaning)".
However, compilers usually are unable to infer the "meaning" of anything. Shouldn't "meaning" be replaced with "signature" or possibly "signature and return type" (depending on the exact definition of signature used)?
O. Jacot-Descombes (talk) 16:57, 19 December 2015 (UTC)
External links modified
[edit]Hello fellow Wikipedians,
I have just modified one external link on Duck typing. Please take a moment to review my edit. If you have any questions, or need the bot to ignore the links, or the page altogether, please visit this simple FaQ for additional information. I made the following changes:
- Added archive https://web.archive.org/web/20081006075246/http://boo.codehaus.org:80/Duck+Typing to http://boo.codehaus.org/Duck+Typing
When you have finished reviewing my changes, please set the checked parameter below to true or failed to let others know (documentation at {{Sourcecheck}}
).
An editor has reviewed this edit and fixed any errors that were found.
- If you have discovered URLs which were erroneously considered dead by the bot, you can report them with this tool.
- If you found an error with any archives or the URLs themselves, you can fix them with this tool.
Cheers.—InternetArchiveBot (Report bug) 11:14, 17 December 2016 (UTC)
Removal of the excessive examples
[edit]The number and verbosity of examples on this page is far more than is required. I could find no other programming-related pages with this many examples. In fact, I believe that it does more harm than good, confusing the subject and making it more difficult to understand what duck typing actually is. Many of the examples are not well put together and either don't demonstrate duck typing at all or don't demonstrate it clearly. Especially damaging to their clarity is their verbosity, as mentioned above, particularly their usage of duck-related phrases. One example could be maintained by the community and be considered valuable, but twenty absolutely cannot. And as long as there are so many examples, it is an invitation for more to be added.
As such, I will be deleting the entire Language Support section. I'll link the revision below, and if a consensus is come to that this section should be restored, it can be found there. Perhaps in the future, a table or list of languages with support for duck typing can be added back, but even that may do more harm than good.
--CrackedP0t (talk) 04:25, 15 June 2017 (UTC)
Paring down examples
[edit]Similarly to the Language Support section, the examples are incredibly verbose to the point of confusion. The output text is needlessly "humorous", and having two examples - in two different languages no less - merely complicates the issue. I'll replace them with a simple Python example, which of course can be edited as needed. — Preceding unsigned comment added by CrackedP0t (talk • contribs) 04:48, 15 June 2017 (UTC)
Cited limitation of protocols is only true for some languages
[edit]This wiki page asserts that a limitation of protocols is that externally defined classes cannot be made to support the interface (without something like an adapter class). While this is true for many languages, it is not true for all. For example, the Swift programming language allows you to extend external classes to support an internal protocol. — Preceding unsigned comment added by Jmacglashan (talk • contribs) 17:18, 6 September 2019 (UTC)
Very Confusing
[edit]The article is too confusing at several levels and should be rewritten, at least partly. It starts by referring to the origin of the expression rather than explaining what it is, then provides an unpolished definition, and ruins the effect with a ludicrous and irrelevant code example.
1. The definition
[edit]With duck typing, an object is of a given type if it has all methods and properties required by that type.
No, that's too restrictive and confusing. Again, this is simpler: With duck typing, an object is defined by its properties. And this should come first, before any comparison to nominal typing.
With nominative typing, an object is of a given type if it is declared as such
No, at best that's a truism. This is simpler: With nominal typing, an object is defined by its declared type.
- Nominal subtyping isn't necessarily incompatible with duck typing, so caution is required there. In particular, nominal subtyping include objects that are identified by their interface, but an interface only specifies a part of an object property - generally a set of methods - and thus are a good example of duck typing. If an interface `Display` declares a method `print`, and the types `Integer` and `Float` both implement this interface, one piece of code accepting a `Display` object is only interested in the `print` method, with no regards to the object type. The interface requirements are the duck test.
- Structural typing isn't mentioned here, but in the
Comparison with other type systems
section.
So perhaps it would be better to include a comparison with nominal typing and subtyping in that section and only keep a brief mention of nominal typing here.
What is duck typing? Duck typing is a programming method that identifies and processes objects according to their properties — such as methods or attributes — rather than to their type. By extension, it may also be a programming method that tries to use some properties of an object without checking its type, optionally handling any error this may trigger.
Then the origin of the expression may be given.
Note also that of the 2nd reference is obsolete (404), and the only remaining reference points to a Python manual.
2. The example
[edit]Just because there is a 'duck' in the expression doesn't make it necessary, nor even preferable, to have a 'duck' in the example.
This simple example in Python 3 demonstrates how any object may be used in any context until it is used in a way that it does not support.
How could that example be of any help to understand what duck typing is? It's not realistic, and it doesn't use the object properties to define the object.
If it can be assumed that anything that can swim is a duck because ducks can swim, a whale could be considered a duck; however, if it is also assumed that a duck must be capable of flying, the whale will not be considered a duck.
This, I think, is the final nail in the coffin. At that point, any person trying to understand the meaning of 'duck typing' has left and is looking for the answer elsewhere.
A better example would be, for instance, how the update
method of dictionaries operate:
class dict(object):
def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
This method accepts another dictionary, an iterable of tuples, or any object implementing either keys()
or __getitem__(self, index)
. It uses duck typing to provide a flexibility that could not be achieved by checking the object's type with isinstance(obj, class_or_tuple)
, or by declaring the object's type in a statically-typed language.