Duck typing

from Wikipedia, the free encyclopedia

Duck typing is a concept of object-oriented programming in which the type of an object is not described by its class , but by the existence of certain methods or attributes .

It is, so to speak, the application of the duck test in computer science, based on James Whitcomb Riley's poem:

"When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck."

"When I see a bird that runs like a duck, swims like a duck, and chatters like a duck, I call that bird a duck."

Duck typing is characteristic of object-oriented scripting languages such as Python , Groovy , PHP, and Ruby .

With duck typing, a check is made at the runtime of the program whether an object supports the corresponding characteristics. This leads, as with all dynamic type system to increased flexibility, but also reduces the possibility of statically at compile-time errors in the program to find. In languages ​​such as Java and D , as well as C # up to version 3.0, it is necessary to specify which interfaces are to be implemented when defining a class . These languages ​​therefore do not allow you to specify after a class has been completed that the class also implements another interface (even if all methods are available and the objects therefore already provide the entire functionality).

In C ++ , function templates offer a kind of duck typing at compile time . Older GCC versions also offered so-called signatures . These can be declared and used like interfaces, but they are independent of the class hierarchy, so that, for example, a duck does not have to be declared again that it can chatter, i.e. that the signature is implemented. This corresponds to the interface structures referred to in Go .

Individual evidence

  1. Glossary - Python 3.7.1 documentation . Retrieved November 8, 2018.