views:

137

answers:

3

Interface (or an abstract class with all the methods abstract) is a powerful weapon in a static-typed language such as C#, JAVA. It allows different derived types to be used in a uniformed way. Design patterns encourage us to use interface as much as possible.

However, in a dynamic-typed language, all objects are not checked for their type at compile time. They don't have to implement an interface to be used in a specific way. You just need to make sure that they have some methods (attributes) defined. This makes interface not necessary, or at least not as useful as it is in a static language.

Does a typical dynamic language (e.g. ruby) have interface? If it does, then what are the benefits of having it? If it doesn't, then are we losing many of the beautiful design patterns that require an interface?

Thanks.

A: 

Sure. Just because it's not necessary doesn't mean it's not useful.

Ignacio Vazquez-Abrams
why should we have an interface for dynamic languages?
Bryan
+2  A: 

I guess there is no single answer for all dynamic languages. In Python, for instance, there are no interfaces, but there is multiple inheritance. Using interface-like classes is still useful:

  • Interface-like classes can provide default implementation of methods;
  • Duck-typing is good, but to an extent; sometimes it is useful to be able to write isinstance(x, SomeType), especially when SomeType contains many methods.
doublep
I like the second point! :)
Bryan
If a class provides default implementations, it's not interface-like because interfaces differ from abstract classes specifically in that they can not contain any implementations.
sepp2k
@sepp2k, I agree. That's not what I call interface.
Bryan
+1  A: 

Interfaces in dynamic languages are useful as documentation of APIs that can be checked automatically, e.g. by development tools or asserts at runtime.

As an example, zope.interface is the de-facto standard for interfaces in Python. Projects such as Zope and Twisted that expose huge APIs for consumption find it useful, but as far as I know it's not used much outside this type of projects.

orip