class DuckTyping < InterfacePolymorphism < UniformInterface

December 18th, 2007

self.respond_to? I really like the concept of the Uniform Interface. One of my favorite things to do is spend hours on my whiteboard (and sometimes days) fiddling with ideas that express what I consider to be elegance. This ranges from macroscopic elegance (ie: the architecture level) to microscopic elegance (ie: the function/method level). Somewhere in the middle lies my fascination with sets, my favorite topic in Discrete Mathematics.

I think one of the reasons I like the Uniform Interface so much is that it groups things together into a set (all things that respond to the same method or methods), which lets you conjure up powerful abstractions at any point in the macroscopic to microscopic elegance scale.

One reason I like REST is because of its HTTP implementation’s Uniform Interface, the most common request methods being CREATE, UPDATE, PUT, DELETE, and HEAD. Programs using MapReduce also use a Common Interface for both the map and reduce functions… and there are many, many more examples.

The difference between the Uniform Interface and Interface Polymorphism is subtle. The Uniform Interface is more general (ie: applying to REST, which is a service), whereas Interface Polymorphism specifically applies to programming. Thus, Interface Polymorphism is a specific kind of Uniform Interface.

The term “Duck Typing” is mentioned in Ruby circles sometimes, and it’s mostly just another name for Interface Polymorphism. This is probably because Ruby has no such thing as an interface. Java on the other hand does, which is how I learned about the concept first. In Java, if a class implements an interface then it absolutely has to define the interfaces methods in its class definition. In Ruby, duck typed methods simply have to be defined by the time an object is called (even if they weren’t there during the objects initial class declaration, or even during the objects initialization). Notice I used the word “object”, but don’t forget that in Ruby a class represented through a constant is an object too. So, the only difference is that Duck Typing is more often used when talking about dynamically adding Interface Polymorphic methods.

Let’s sum it all up with a Ruby class definition and some inheritance.

class DuckTyping < InterfacePolymorphism < UniformInterface
end

Leave a Reply