CSC/ECE 517 Fall 2012/ch2b 1w59 nm
SaaS - 3.7. Mixins and Duck Typing
Duck Typing
[1]
What is Duck Typing
“If a object walks like a duck, quacks like a duck then treat it as a duck”
This is the ‘mantra’ of Ruby language and the most pleasing aspect of the language. What it means is that, whether an object responds to a method?, is only important and not the type of the object. If a dragon responds to methods like swim and quacking, ruby is happy to treat dragon as a duck without having a concern of whether it actually is a duck or not. This gives powerful tools for a ruby programmer.
This is possible in Ruby because we don’t declare the 'Type[2] of variables or methods like in JAVA; in Ruby, everything is an object and each object can be individually modified, irrespective of its implementation in the class to which it belongs.
Consider the following example taken from the SAAS lecture:
my_list.sort [5, 4, 3].sort ["dog", "cat", "rat"].sort [:a, :b, :c].sort
Here, the same function, sort, is responding to an array of integers, strings and literals. This is classic Ruby duck-typing at work. How sort works is that it compares the elements which are needed to be sorted. So as long as the elements can be compared, sort function works. In the above example, the array of integers, strings and literals implement the comparison operator and hence the same sort function works for all of them.
Why in Ruby and not in JAVA?
The reason for duck-typing to be easily possible and implemented in language like Ruby and not in language like JAVA is that these 2 languages treat ‘type’ differently. In JAVA or C++, type means class. When someone asks the type of “abc”, we say it is String. So, such language allows String objects to refer to only other String objects. String a; a will never be allowed to refer to anything other than a string, like a=5.
While in Ruby, type refers to how the object reacts to a method or in other words does the object have a particular capability. Type refers to this capability. While a class to which the object belongs provides the initial capabilities, from that point on, the object is free to extend its capabilities independently of its pre-defined class. So,
a= ”abc” a= 5 are two perfectly acceptable statements in Ruby.
This is duck-typing.
A classic example[3] of how a scripting language, JavaScript, not implementing duck-typing can lead to some bad code.