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?
p 'Playing music!'
endclass IPhone < BluetoothDevice
p 'Connecting my iPhone using Bluetooth...'
endclass Android < BluetoothDevice
p 'Connecting my Android using Bluetooth...'
@phone = phone
Then we can use any phone in our car that can connect and play music:
This is the output:
"Connecting my iPhone using Bluetooth..."
"Connecting my Android using Bluetooth..."
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!