Talk:Duck typing
From Wikipedia, the free encyclopedia
[edit] 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)
[edit] 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)
[edit] 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... --P3d0 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)
[edit] 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)
[edit] 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)
[edit] 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.
[edit] 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)
[edit] 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)
[edit] 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)
-
[edit] 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)
[edit] 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)
[edit] In Java
90% self-flattery. 203.154.48.180 08:43, 14 July 2007 (UTC)
[edit] 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)
[edit] 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)
[edit] 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)
[edit] 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)
[edit] 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)
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)
[edit] 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)
[edit] 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)
[edit] 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)
[edit] 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)
[edit] 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)
class DuckWithNoLegs {
Quack() { .. }
}
performQuack(new DuckWithNoLegs()); // fails because duck interface requires walking ability
- it is my understanding that for performQuack() should take legless ducks under true duck typing. Talyian (talk) 17:19, 24 March 2008 (UTC)
- I'm not so sure if that's really part of the 'duck typing', or simply part of the 'dynamic typing' that usually goes hand-in-hand with duck typing. The static typing checks whether 'it's a duck', and we defined 'duck' as 'walks and quacks'. Your DuckWithNoLegs doesn't walk like a duck, so I don't think it's that odd it's not considered a duck... indeed a dynamic language would in this case not check for 'Duck', but merely for 'ObjectThatQuacks' --195.35.227.61 (talk) 08:44, 25 March 2008 (UTC)
- If you don't use it then it isn't required in duck typing. if all you are doing is calling Quack then Duck typing would not require anything else. See the DuckDecoy class above, which doesn't need a defecate method. --Paddy (talk) 13:08, 25 March 2008 (UTC)
[edit] 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)