Duck typing


In computer programming, an object is usually suitable based on its type. For instance, we cannot use a string type to sum numbers, but we can do lots of other actions suitable for strings.

On the other side, duck-typing does not define an object by its type, but by the methods and properties it has. So, if the dog in the image has a duck beak (property) and it quacks (method), then it is not a dog, it is a duck. This is called “duck test”.

This design rule is to avoid concerning about passing a variable of a certain type to a method. We can just pass any type, and the method will call its methods directly. This practice relies essentially on well written documentation, clear code and testing to ensure correct use.

Let’s see this concept in action. Suppose that we have 2 mobile phones and we want to play music in our car. We will probably use Bluetooth regardless of the phone brand, right?

Then we can use any phone in our car that can connect and play music:

This is the output:

Notice that in the Car constructor we did not check the Phone object. We just saved it in a variable and used it directly when connecting and playing music. Duck-typing in action!

Did you like it? Please share it:

Get my ebook for free

10 ideas that helped me become a better developer (and may help you too)

Subscribe to my mailing list and get my ebook on 10 ideas that helped me become a better developer.

About Me

David Morales

David Morales

I'm David Morales, a computer engineer from Barcelona, working on projects using Ruby on Rails and training on web technologies.

Learn More