Duck Typing

While browsing the net, I found that Typemock Isolator 5.1.1 has been released, which is a mocking framework that I should try one day.

What I’m interested in is its ability to “swap” calls between real and fake objects even if they don’t implement the same interface, like this:

var duck = new Duck(); // The real, untestable class, with a Talk() method
var dummy = new Dummy(); // The fake, testable class, with another Talk() method
Isolate.Swap.CallsOn(duck).WithCallsTo(dummy);
Assert.AreEqual("Quack", dummy.Talk()); // Then the dummy is a duck

I guess the Isolate class is “borrowed” from Ruby, but anyway, it makes testing easier.

This can be possible by applying the concept of “Duck Typing” which was named as James Whitcomb Riley said


If it walks like a duck and quacks like a duck, I would call it a duck

 

So, regardless of the properties and methods of both the dummy and the real duck, a dummy can be considered a duck if it satisfies the properties and methods of a real duck in the current context, or in other words; it does not have to inherit from a duck nor satisfy all behavior of a real duck, but only what we need right now [Talk()]

Duck typing is a principle of Dynamic Typing (Which I plan to blog about next), and it is a heavily used in Dynamic Languages like Python, Ruby.

It is sometimes used in Static Languages, and may be more often than we expect. Here is a blog about Duck Notation in C# in which we find out that iterators in a foreach statement use duck typing. Also in BOO you can define a variable as duck.

Currently there is an open source project to enable duck-typing in C#, and also it is planned to be in the upcoming C# 4.0

kick it on DotNetKicks.com

About these ads

2 thoughts on “Duck Typing

  1. Pingback: Dynamic Typing | Technical Thoughts

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