NOTE : This post may contains repeated and boring stuff for those who already have the programming practice of DuckTyping.

What is Duck Typing ?
Duck Typing is Dynamic Typing
In ruby we do not declare the type of the variable. It automatically becomes the object of the related class. For example, if we assign str = “hello string” then the variable str will automatically becomes the object of class String, that we can confirm by issuing str.class. But according to Duck Typing philosophy even Classes are not Types.
That is the basic rule of Duck Typing is that THE TYPE OF OBJECT IS DETERMINED BY WHAT IT CAN DO, NOT BY ITS CLASS. Lets exemplify the statement…

now here the object obj is a NilClass object but (in ruby) it will be wrong to say that obj is a NilClass type object. The statement is confining the tasks that can be performed by it. Coz we can have the object obj as a NilClass object and still performing singleton functionalities declared over it. Like …

So, even a nil object can wish you good morning! Here a method wish has been added to a nil object. But it will not be available for all nil objects, or will that be ? Well, thats a homewok for you!!
Check this out, in this case the wish method will be available for all the nil objects… and the reason is that all the nil objects actually points to a same preserved nil object in the ObjectSpace but not creates a new object everytime like in most cases. Well, i will discuss more deeply regarding the ObjectSpace very soon.

Moreover, extending the modules over an object both at run time and compile time is itself a functionality supporting the statement that Classes are not types and this is what Duck Typing is.

Why known as Duck Typing ?

Alex Martelli, a member of the Python Software Foundation , have given the name DuckTyping to this approach in reference with Duck Test … which says that When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
So, if an object is behaving like string the it is string type object but not if only it have the class as String.

Share this: