What’s 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?

class BluetoothDevice
def playMusic
p 'Playing music!'
end
end
class IPhone < BluetoothDevice
def connect
p 'Connecting my iPhone using Bluetooth...'
end
end
class Android < BluetoothDevice
def connect
p 'Connecting my Android using Bluetooth...'
end
end
class Car
def initialize(phone)
@phone = phone
end

def connect
@phone.connect
self
end

def playMusic
@phone.playMusic
end
end

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

Car.new(IPhone.new).connect.playMusic
Car.new(Android.new).connect.playMusic

This is the output:

"Connecting my iPhone using Bluetooth..."
"Playing music!"
"Connecting my Android using Bluetooth..."
"Playing music!"

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!

Computer engineer. Working as a web developer since 2000.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store