Duck Typing

Mochammad Alamsyah
1 min readAug 28, 2018

--

From Geek and Poke
If it looks like a duck, and quacks like a duck, then its probably a duck.

In computer programming with object-oriented programming languages, duck typing is a style of typing in which an object’s methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. — Wikipedia

The idea of duck typing, is that in dynamical languages like ruby and javascript, the language doesn’t care what the object it calls a method on is, as long as it understands that method call. Furthermore, we can substitute one object for another at runtime, allowing us to dynamically choose which object needs to be involved when the program is run.

For a example in this ruby code:

Here we choose an object by sampling our array. But it doesn’t matter which object is returned so we can call .fly on both. We say that these two classes are duck typed. They share the same public interface and so can easily be exchanged for each other.

--

--