| advertise add site services publishers database health videos | ![]() | about toolbar stats live show health store more stuff JOIN/LOGIN |
diabetes, type 2 diabetes, type 1 diabetes, diabetes diets information tbfinc.com | SMA Clinical Research Center about Type 1, Type 2, Type 3 columbiasma.org | Mesothelioma Help Center | Types of Mesothelioma | Types of Mesothelioma... mesotheliomahelpcenter.or... |
In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see History below), which may be phrased as follows:
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. Duck typing is aided by habitually not testing for the type of arguments in method and function bodies, relying on documentation, clear code, and testing to ensure correct use. Users of statically typed languages new to dynamically typed languages are usually tempted to add such static (before run-time) type checks, defeating the benefits and flexibility of duck typing, and constraining the language's dynamism.
[edit] Concept exampleConsider the following pseudo-code for a duck typed language: function calculate(a, b, c) => return (a+b)*c example1 = calculate (1, 2, 3) example2 = calculate ([1, 2, 3], [4, 5, 6], 2) example3 = calculate ('apples ', 'and oranges, ', 3) print to_string example1 print to_string example2 print to_string example3 In the example, each time the 9 [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] apples and oranges, apples and oranges, apples and oranges, Thus, duck typing allows polymorphism without inheritance. The only requirement that function class Duck: def quack(self): print "Quaaaaaack!" def feathers(self): print "The duck has white and gray feathers." class Person: def quack(self): print "The person imitates a duck." def feathers(self): print "The person takes a feather from the ground and shows it." def in_the_forest(duck): duck.quack() duck.feathers() def game(): donald = Duck() john = Person() in_the_forest(donald) in_the_forest(john) game() [edit] Duck typing in statically typed languagesCertain usually statically typed languages such as Boo and the version 4 release of C# have extra type annotations[1][2] that instruct the compiler to arrange for type checking of classes to occur at run-time rather than compile time, and include run-time type checking code in the compiled output. Such additions allow the language to enjoy most of the benefits of duck typing with the only drawback being the need to identify and specify such dynamic classes at compile time. [edit] Comparison with other type systems[edit] Structural type systemsDuck typing is similar to but distinct from structural typing. Structural typing is a static typing system that determines type compatibility and equivalence by a type's structure, whereas duck typing is dynamic and determines type compatibility by only that part of a type's structure that is accessed during run time. [edit] InterfacesInterfaces can provide some of the benefits of duck typing but duck typing is distinct in that no explicit interface is defined. For example, if a third party Java library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you've defined yourself, whereas duck typing would allow this. [edit] Templates or generic typesTemplate functions or methods apply the duck test in a static typing context; this brings all the advantages and disadvantages of static versus dynamic type checking 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 Java language's generics. [edit] CriticismAn oft-cited criticism is this:
Proponents of duck typing like Guido van Rossum argue that the issue is handled by testing, and the necessary knowledge of the codebase required to maintain it[3][4]. Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically typed versus statically typed programming language semantics. [edit] HistoryAlex Martelli made an early (2000) use of the term in a message to the comp.lang.python newsgroup. He also highlighted misunderstanding of the literal duck test, which may indicate that the term was already in use.
[edit] Implementations[edit] In C#In C# 4.0 the compiler and runtime collaborate to implement dynamic member lookup. [edit] In ColdFusionThe web application scripting language ColdFusion allows function arguments to be specified as having type any. For this sort of argument, an arbitrary object can be passed in and method calls are bound dynamically at runtime. If an object does not implement a called method, a runtime exception is thrown which can be caught and handled gracefully. In ColdFusion 8, this can be picked up as a defined event onMissingMethod()rather than through an exception handler. An alternative argument type of WEB-INF.cftags.component restricts the passed argument to be a ColdFusion Component (CFC), which provides better error messages should a non-object be passed in. [edit] In Common LispCommon Lisp provides an object-oriented extension (Common Lisp Object System, or shorter CLOS). The combination of CLOS and Lisp's dynamic typing make duck typing a common programming style in Common Lisp. With Common Lisp one also does not need to query the types, since at runtime an error will be signaled when a function is not applicable. The error can be handled with the Condition System of Common Lisp. Methods are defined outside of classes and can also be defined for specific objects. (defclass duck () ()) (defmethod quack ((a-duck duck)) (print "Quaaaaaack!")) (defmethod feathers ((a-duck duck)) (print "The duck has white and gray feathers.")) (defclass person () ()) (defmethod quack ((a-person person)) (print "The person imitates a duck.")) (defmethod feathers ((a-person person)) (print "The person takes a feather from the ground and shows it.")) (defmethod in-the-forest (duck) (quack duck) (feathers duck)) (defmethod game () (let ((donald (make-instance 'duck)) (john (make-instance 'person))) (in-the-forest donald) (in-the-forest john))) (game) The usual development style of Common Lisp (by using a Lisp REPL like SLIME) allows also the interactive repair: ? (defclass cat () ()) #<STANDARD-CLASS CAT> ? (quack (make-instance 'cat)) > Error: There is no applicable method for the generic function: > #<STANDARD-GENERIC-FUNCTION QUACK #x300041C2371F> > when called with arguments: > (#<CAT #x300041C7EEFD>) > If continued: Try calling it again 1 > (defmethod quack ((a-cat cat)) (print "The cat imitates a duck.")) #<STANDARD-METHOD QUACK (CAT)> 1 > (continue) "The cat imitates a duck." This way software can be developed by extending partially working duck typed code. [edit] In Objective-CObjective-C, a cross between C and Smalltalk, allows one to declare objects of type 'id' and send any message to them, like in Smalltalk. The sender can test an object to see if it responds to a message, the object can decide at the time of the message whether it will respond to it or not, and if the sender sends a message a recipient cannot respond to, an exception is raised. Thus, duck typing is fully supported by Objective-C. [edit] In PythonDuck typing is heavily used in Python. The Python's Glossary defines duck typing as follows:
The standard example of duck typing in Python is file-like classes. Classes can implement some or all of the methods of The EAFP principle describes the use of exception handling. For example instead of checking to see if some purportedly Duck-like object has a quack() method (using try: mallard.quack() except (AttributeError, TypeError): print "mallard can't quack()" Advantages of this approach are that it encourages the structured handling of other classes of errors (so, for example, a mute Duck subclass could raise a "QuackException" which can be added to the wrapper without delving more deeply into the logic of the code, and it handles situations where different classes of objects might have naming collisions for incompatible members (for example, Mallard the purported medical professional might have a boolean attribute which classifies him as a "quack=True"; an attempt to perform Mallard.quack() would raise a TypeError)). In the more practical examples of classes which implement file-like behavior the use of Python's exception handling facilities is generally preferred for handling a wide variety of I/O errors that can occur due to numerous environmental and operating system issues that are outside of the programmer's control. Here again the "duck typing" exceptions can be caught in their own clauses alongside the OS, I/O or other possible errors without complicated testing and error checking logic. Simply stated: provided you can perform the job, we don't care who your parents are. [edit] References
[edit] External links
|
| ↑ top of page ↑ | about thumbshots |