Duck Typing — What It Means Exactly

# Screw the duck example

Liu Zuo Lin
CodeX

--

How many of you have heard the famous phrase:

If it walks like a duck and it quacks like a duck, then it must be a duck

And went ‘wait what’? I unfortunately did when I read this the first couple of times, and didn’t properly understand duck typing til quite a while later. So this article goes out to all of yall who are still somewhat confused about duck typing.

When Do We Use Duck Typing?

When we cannot explicitly check the type of something, but we want to make a good guess what type it is.

For instance, say I’m working on a web app, and I want to check whether the user’s browser is Chrome/Firefox/Brave or whatever. And I don’t have a function to tell me exactly which browser my user is using.

So What Exactly Is Duck Typing?

I currently don’t know what type something is, and can’t check it exactly.

But I can extract some features from this ‘something’

Based on the features I extract, I can now make a good guess what type this ‘something’ is.

It might not be 100% correct, but it’s good enough

A Real Life Example —…

--

--