Jump to content

Duck typing

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by CrackedP0t (talk | contribs) at 04:27, 15 June 2017 (Removed Language Support). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, duck typing is an application of the duck test in type safety. It requires that type checking be deferred to runtime, and is implemented by means of dynamic typing or reflection.

Duck typing is concerned with establishing the suitability of an object for some purpose. With normal typing, suitability is assumed to be determined by an object's type only. In duck typing, an object's suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object.[citation needed]

Concept examples

Consider 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], 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 calculate function is called, objects without related inheritance may be used (numbers, lists and strings). As long as the objects support the "+" and "*" methods, the operation will succeed. If translated to Ruby or Python, for example, the result of the code would be:

9
[1, 2, 3, 1, 2, 3]
apples and oranges, apples and oranges, apples and oranges,

Thus, duck typing can work the same as polymorphism, but without inheritance. The only restriction that function calculate places on its arguments is that they implement the "+" and "*" methods.

The duck test can be seen in the following example (in Python). As far as the function in_the_forest is concerned, the Person object is a duck:

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 name(self):
        print("John Smith")

def in_the_forest(duck):
    duck.quack()
    duck.feathers()

def game():
    donald = Duck()
    john = Person()
    in_the_forest(donald)
    in_the_forest(john)

game()

In statically typed languages

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

Comparison with other type systems

Structural type systems

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

The OCaml, Scala, Go, Elm,[3] and Gosu languages support structural typing to varying degrees.

Protocols and Interfaces

Protocols and interfaces 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 library implements a class that cannot be modified, a client cannot use an instance of it with an interface unknown to that library even if the class does in fact satisfy the interface requirements. (A common solution to this problem is the Adapter pattern.) Duck typing would allow this. Again, all of an interface must be satisfied for compatibility.

Templates or generic types

Template, or generic 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 languages C++ and D with templates, which developed from Ada generics.

Criticism

Criticism of the term itself

Use of the term "duck typing" has been considered superfluous in light of the fact that other terms, such as dynamic binding, express the concept more clearly.[4] To proponents of static type checking, duck typing suggests the absence of typing, making its incorporation of the term typing appear incoherent.

History

Alex Martelli made an early (2000) use of the term in a message to the comp.lang.python newsgroup:

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.

See also

References

  1. ^ Boo: Duck Typing Archived October 6, 2008, at the Wayback Machine
  2. ^ "Anders Hejlsberg Introduces C# 4.0 at PDC 2008". Retrieved 30 January 2017.
  3. ^ Czaplicki, Evan. "Core Language · An Introduction to Elm". Retrieved 30 January 2017.
  4. ^ Lippert, Eric (2 Jan 2014). "What is "duck typing"?". Fabulous adventures in coding. Retrieved 25 May 2016. ... the whole idea of duck typing is fundamentally incoherent ...'

External links