In
static typed languages like
Java,
interfaces are used to define common sets of
methods which are common across different classes. For example:
// define a type of object which can talk
interface Talkable {
public void talk();
}
class Duck implements Talkable {
public void talk() {
System.out.println("quack!");
}
}
class Dog implements Talkable {
public void talk() {
System.out.println("bark!");
}
}
class Foo {
// given a type of object which can talk, make it talk
public static void talk(Talkable animal) {
animal.talk();
}
public static void main(String[] args) {
talk(new Duck());
talk(new Dog());
}
}
As the language is statically typed, when
compiling the program, the
compiler needs to know the type in order to know which method to call when method calls are invoked (animal.talk() in the example above).
Duck Typing
If it looks like a duck, walks like a duck, and quacks like a duck, then it's probably a duck.
- An American Saying
Dynamically typed languages like
Ruby do not have these restrictions. As a result, constructs like interfaces are generally unneccessary. A method can simply be invoked. Here is a ruby example:
class Duck
def talk
puts "quack!"
end
end
class Dog
def talk
puts "woof!"
end
end
def talk(animal)
animal.talk()
end
talk(Dog.new())
talk(Duck.new())
This is known as
Duck Typing within the Ruby community.
Rubyists encourage checking if methods exist rather than checking if an object is of a particular
class. After all, in the above example, the "Talkable" interface type is defined by its methods anyway - why not just check if they exist?
def can_talk?(animal)
return animal.respond_to?(talk)
end
This kind of strong preference for dynamic typing can be seen throughout the
Ruby language.
Variables do not have explicit types given to them, for example, and you can dynamically
extend objects through the use of
singleton methods. Classes are used more as a way to create objects, rather than defining them.
Some people argue that the use of explicit type checking is useful in creating more well defined and robust software. However, in a lot of cases the need to constantly cast objects and define such interfaces gets in the way. Better results can probably be obtained through the use of Unit Tests anyway.
More on Duck Typing:
- http://c2.com/cgi/wiki?DuckTyping
- http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/81924