Talk:Duck typing
Computing Unassessed | ||||||||||
|
Identity
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
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?
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
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?! :-)
Perl?
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?
- 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
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
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
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
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.
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
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
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
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)
Duck typing in programming languages
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
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
- 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
- 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
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#
"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
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
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
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)
.NET not a language
.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
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
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
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!?!?
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
It is good English. --Paddy (talk) 17:05, 15 July 2009 (UTC)
C# implementation.
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
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
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
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
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
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?
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
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
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)
What is Duck Typing ?
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.
- 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 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)