What Is Duck Typing? Everything You Need To Know

what is duck typing?
Written By: Grant Darling
September 10, 2021

As you can see above, although we intended to use our loop for a duck, the code had no problem executing the flys() method for our goose object as well. However, since our goose can't quack, python threw an error. 

In other words, since python allows duck typing it assumed that since the Goose fly's like a duck, it must be a duck. The language later decides that since it doesn't quack like a duck, it can't be a duck.

This is decided at runtime. Which is why the fly() message will execute before throwing the error.

Is Duck Typing Bad And When Is It Useful?

So, is duck typing bad? As with everything in programming, it depends. Duck typing is not inherently good or bad and can be argued on both oppositions. 

Disadvantages of Duck Typing

The biggest disadvantage of duck typing is that it leaves the responsibility of writing clean error-free code in the hands of the developer. This can be a big issue if working with an inexperienced programmer or when taking on a project that was passed along to you.

Poorly written duck typing code can lead to long and painful hours debugging a program that should never have needed debugging to begin with. This can then lead to costly development time and more working hours. 

Additionally, if you had a type system that checked for errors on compile, it makes it much easier for IDEs to complain as you're typing. Allowing you to find bugs faster and making them much easier to fix. With duck typing, errors are discovered during runtime, which makes it harder to go back and fix past mistakes. 

Advantages of Duck Typing

Alternatively, duck typing has plenty of positives. After all, there is a reason that so many newer languages allow this functionality. The first advantage is that it leads to fewer lines of code. This makes it look cleaner; thus making your code easier to read and faster to write.

It can be hard to see the advantages of duck typing until you have used languages with and without it. Afterward, you will realize it makes your job a lot easier when you're not dealing with interfaces (such as in Java or C#) or keeping track of what type your object is. Assuming you don't fall into bad practices, it really is useful functionality!

What Languages Use Duck Typing?

Leave a Reply

Your email address will not be published. Required fields are marked *

Copy link
Powered by Social Snap