Skip to content
Search

Duck typing

lastmod 2015-06-10created 2015-06-101 edits

In computer programming, duck typing is a kind of dynamic typing in which an object's set of variables and methods determines the object's type. Instead of distinguishing types by class inheritance or interface implementation, duck typing treats an object as belonging to a type if it has the variables and methods appropriate to that type. The term "duck typing" comes from the duck test, which can be expressed as follows. ("Duck" is the English word for the bird called ori in Korean.)

만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라고 부를 것이다.

In duck typing, how an object is used matters more than its type. For example, in a programming language without duck typing, you can write a function that takes an object of type Duck as an argument and calls the object's walk method and quack method in turn. In a language that supports duck typing, on the other hand, the same function can be written so that it does not check the type of the object it receives as an argument. If the object does not have the two methods at the moment the walk or quack method is called, a runtime error occurs; if both methods are properly implemented, the function works normally. This carries the implication that if the object received as an argument has a walk method and a quack method, it will be treated as a Duck type. Because this matches the idea of the duck test quoted above, it was named duck typing.

Favorite site