Home > Uncategorized > Duck Typing

Duck Typing

Note: A lot of this stuff is CTRL+C, CTLR+V. I have just tried to consolidate stuff into one single article. I can come back to this one article & coherently read this from one single article, instead of jumping over a dozens of pages and get lost. So I do not claim credits for any of the stuff here.

If it walks like a duck and quacks like a duck, I would call it a duck.‘ Now let us try to add some context to the quote using an example from ‘Pick-Axe’ book[1].

Given the code:

class Customer
          def initialize(first_name,last_name)
                    @first_name = first_name
                    @last_name = last_name
          end
          def append_name_to_file(file)
                    file << @first_name << " " << @last_name
          end
end

and the test code,

require’test/unit’
require’addcust’
class TestAddCustomer < Test::Unit::TestCase
          def test_add
                    c = Customer.new("Ima", "Customer")
                    f =""
                    c.append_name_to_file(f)
                    assert_equal("Ima Customer",f) 
          end
end

The C# compiler will complain on similar C# code, because  it was expecting a File class or a derivative of the File class or a class which implements the File interface. It was really great that the C# compiler complained and we caught this error @ compile time. The conservative in us becomes really happy.

The code actually runs and ruby. And it becomes a valid unit test. Yes you can pass a string where you were expecting a File object. What?? Does the ruby string inherit from file? Or do all the objects in ruby inherit from something like ‘System.Object’ which responds to the operator ‘<<‘. The answer is No. In ruby the interface / inheritance hierarchy is not used by the type system. All the type system is worried about is that the object can respond to the ‘<<‘ operator. 

In other words you do not have to inherit from the ‘Duck’ base class or implement the ‘Duck’ interface. As long as your object can respond to the ‘quack’ and the ‘walk’ methods we can use it wherever we had intended to use a Duck type. So ‘Duck Typing’ turned the adverse situation where the error couldn’t have been caught @ compile-time into an advantage by cleverly leveraging it to easily unit test the customer object. What if the object passed to the ‘file’ parameter cannot respond to the ‘<<‘ operator. It fails @ runtime in a dramatic fashion and let you know why it failed.

To all those conservatives(I am one of those mind you) who might insist that C# would have forced you to use an interface here which means it is loosely coupled. Using an interface for everything is debatable. See this previous article where I had blogged about this suggestion from NetObjectives on progamming to an interface not to an implementation. ‘Duck Typing’ helps you to avoid scenarios where you have to go for interfaces which exactly match the public interface and have only one concrete implementation. These kind of scenarios exist just because you have to shut-up a complaining compiler. Also the liberal in you will say interfaces help you to just remove ‘synactic coupling’ and not ‘sematic’. Let us re-read the definition of duck typing now and see if we can make more sense of it.

StructuralTyping[2]: Types are defined by the structure of values (two differently-named types which are arrays of 5 ints are the same type

Duck Typing[3]: Similar to structural typing, but distinct from Structural typing, because in Structural typing schemes type compatibility and equivalence are determined by the type’s structure; whereas in duck typing, type compatibility and equivalence are determined only by that part of a type’s structure that is accessed.

[1] Programming Ruby: The Pragmatic Programmer’s guide – http://www.pragprog.com/titles/ruby
[2] Types of Typing – http://c2.com/cgi/wiki?TypesOfTyping
[3] Duck Typing – http://en.wikipedia.org/wiki/Duck_typing#Comparison_with_Structural_type_systems

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: