Duck typing
   HOME

TheInfoList



OR:

Duck typing in computer programming is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
can be used for a particular purpose. With nominative typing, an object is ''of a given type'' if it is declared to be (or if a type's association with the object is inferred through mechanisms such as
object inheritance In object-oriented programming, inheritance is the mechanism of basing an Object (computer science), object or Class (computer programming), class upon another object (Prototype-based programming, prototype-based inheritance) or class (Class-based ...
). In duck typing, an object is ''of a given type'' if it has all
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
and properties required by that type. Duck typing can be viewed as a usage-based structural equivalence between a given object and the requirements of a type. See
structural typing A structural type system (or property-based type system) is a major class of type systems in which type compatibility and equivalence are determined by the type's actual structure or definition and not by other characteristics such as its name ...
for a further explanation of structural type equivalence.


Example

This is a simple example in
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
3 that demonstrates how any object may be used in any context, up until it is used in a way that it does not support. class Duck: def swim(self): print("Duck swimming") def fly(self): print("Duck flying") class Whale: def swim(self): print("Whale swimming") for animal in uck(), Whale() animal.swim() animal.fly() Output: Duck swimming Duck flying Whale swimming AttributeError: 'Whale' object has no attribute 'fly' So, if we assume everything that can swim is a duck because ducks can swim, we will consider a whale to be a duck, but, if we also assume it has to be capable of flying, the whale won’t be considered to be a duck.


In statically typed languages

In some statically typed languages such as Boo and D, class type checking can be specified to occur at run time rather than compile time.


Comparison with other type systems


Structural type systems

Duck typing is similar to, but distinct from,
structural typing A structural type system (or property-based type system) is a major class of type systems in which type compatibility and equivalence are determined by the type's actual structure or definition and not by other characteristics such as its name ...
. Structural typing is a
static typing In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
system that determines type compatibility and equivalence by a type's structure, whereas duck typing is
dynamic Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dyna ...
and determines type compatibility by only that part of a type's structure that is accessed during
run time Run(s) or RUN may refer to: Places * Run (island), one of the Banda Islands in Indonesia * Run (stream), a stream in the Dutch province of North Brabant People * Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
. The
TypeScript TypeScript is a free and open source programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are ...
,
Elm Elms are deciduous and semi-deciduous trees comprising the flowering plant genus ''Ulmus'' in the plant family Ulmaceae. They are distributed over most of the Northern Hemisphere, inhabiting the temperate and tropical-montane regions of North ...
, and
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
languages support structural typing to varying degrees.


Protocols and interfaces

Protocols and interfaces provide a way to declare, explicitly, that some methods, operators, or behaviors need to be defined (e.g. must have a ''quack()'' method). 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 In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface. It is often ...
. In contrast, under duck typing, the object would be accepted directly, without the need for an adaptor.


Templates or generic types

Template Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs ...
, or
generic Generic or generics may refer to: In business * Generic term, a common name used for a range or class of similar things not protected by trademark * Generic brand, a brand for a product that does not have an associated brand or trademark, other ...
functions or methods apply the duck test in a
static typing In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
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 runtime'' need to be implemented, while templates require implementations of all methods that ''can not be proven
unreachable In computer programming, unreachable memory is a Block (data storage), block of dynamic memory allocation, dynamically allocated memory where the computer program, program that allocated the memory no longer has any reachable pointer (computer ...
at compile time''. In languages like Java, Scala, and Objective-C,
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in ...
can be used to inspect whether objects implement methods or even add necessary methods at runtime. For example,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
'
MethodHandle API
can be used in this manner.


See also

*
Extension method In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-orie ...
* UFCS *
Loose coupling In computing and systems design, a loosely coupled system is one # in which components are weakly associated (have breakable relationships) with each other, and thus changes in one component least affect existence or performance of another comp ...
*
Monkey patch Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaSc ...
*
Dynamic programming language In computer science, a dynamic programming language is a class of high-level programming languages, which at runtime execute many common programming behaviours that static programming languages perform during compilation. These behaviors co ...


References

{{DEFAULTSORT:Duck Typing Articles with example pseudocode Object-oriented programming Type theory Articles with example Python (programming language) code