views:

184

answers:

8

Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

+2  A: 

One use that I have for interfaces is to help with unit testing framework classes that are hard to mock. I will create an interface that works basically the same as the framework class and a wrapper class that implements the interface. The constructor of the wrapper class takes an instance of the framework class as an argument. The wrapper delegates the interface functionality it supports to the framework class, but I implement to my interface instead of the framework. Using the interface makes it easy for me to mock out the wrapper class's functionality in my unit tests -- either using a mocking framework or by providing a fake class that also implements the interface and supplying it via dependency injection to any classes that would normally rely on the framework class.

tvanfosson
+4  A: 

Interfaces are interesting because you can allow 2 classes to implement the same methods. Lets look at an example.

Say I have a base class called Animal. All animals breathe, and communicate. Now lets say I have 3 classes, called Dolphin, Human, and Tiger. All of theses animals breathe and communicate. But I want to implement a walking method for the Human and Tiger. Dolphins cant walk. So I inherit the IWalk method for the latter two, and when I compile the class, I HAVE to implement the methods specified in the interface, or it won't compile. It's a contract saying, "If I want to implement this class, I have to implement these methods."

BBetances
-1: no mention of which interfaces are being implemented. Do you mean "implement the IWalk interface", not "inherit the IWalk method"?
Alabaster Codify
@jamesbrady: Depending on your choice of language (e.g. C++) you inherit an interface, there is no implements keyword. Be a sport and remove the -1, the question is language agnostic.
Binary Worrier
How is this interesting or realistic. People almost never write classes representing animals, unless it's for some class assignment. How is this marked right, when it doesn't answer the original question.
Kibbee
+1  A: 

They allow polymorphism without some of the bad sides of inheritance.

What do I mean by bad sides of inheritance?
Code and Data inherited down a long chain (making it less obvious).
Inherited members that are over-ridden somewhere in the inheritance tree.

How can you use polymorphism?
To avoid repeating yourself. Create functions, switches, or conditionals which use the interface instead of the objects that implement the interface.

Java Specific
In Java, it often makes sense to use interfaces as a way to get multiple-inheritance.
This makes sense if something naturally fits into two categories and you have separate behavior expected for both of them.

Some Java Examples from the Web
http://home.cogeco.ca/~ve3ll/jatutor5.htm
http://java.freehep.org/lib/freehep/doc/root/index.html
http://www.codeguru.com/java/tij/tij0080.shtml

John Mulder
A: 

As tvanfosson mentioned, there very useful for mocking, also if you writing a library that depends on outside configuration you can make an IFooProvider and have the calling program implement it.

flukus
A: 

I assume you mean "interface" in the programming language sense rather than in the other senses, e.g. "User Interface".

An interface in languages like Java or C# serves two purposes. The first is to provide a contract for a type to implement; a suite of method names and signatures that the type provides to other types that use it. The second is to provide polymorphism upon that interface for the type. For example, if I have a type that implements the IFoo interface, I can pass an instance of that type to another class where the other class needs only know about the IFoo interface rather than every detail of my class that implements IFoo.

Randolpho
A: 

Interfaces are useful when you want to allow interoperability between two classes that do not share a common class hierarchy.

A good example of this is java.lang.CharSequence. Lots of other things can be abstractly treated as strings, but it wouldn't be correct to subclass String to do so. In fact String is final so it couldn't be done anyway.

Some time around JDK 1.4 (I beleive?) the CharSequence interface was introduced. Now String, StringBuffer, CharBuffer and lots of other existing classes in the JDK implement it. With that, new methods could be added to other APIs which accept CharSequence, allowing them to abstractly handle all of these in a unified way.

You can also implement this interface yourself and use it the same way. It's far more flexible to implement a common interface than try and force things to extend from a specific base class (or sometimes it's impossible).

Mark Renouf
+1  A: 

An interface (or an abstract class) is a contract you pass with the compiler. This contract says :

-- Well, compiler, make sure that all the classes that will implement this will provide at least everything that is defined in this interface !

With this insurance, you can then write methods that manipulate objects of any class implementing this interface :

 void myGenericMethod( IAnInterface genericObject )

myGenericMethod method can use any member of the interface IAnInterface. It will never throw a runtime error (any missing member will have been caught by the compiler).

Utility : to give some common behavior to different objects. You may want for example to be able to call a method named GetID on any of your objects, being it a BankAccount, a ComputerCluster or an AirplaneTrip.

You will find a lot of useful interface usages in most design patterns. MSDN provides some hints about when you should use an interface here : http://msdn.microsoft.com/en-us/library/27db6csx.aspx

Sylvain
A: 

I prefer to regard an interface as a description of a role to be fulfilled by each instance of an implementing class, independent of any implementation inheritance hierarchy.

By way of analogy, you can describe a "screen pass" football play in terms of how certain positions on the team interact. That description, in terms of position (or role or interface) is independent of which player happens to be playing the position at a given time. It's also independent of whether the team happens to have some talented players who can play more than one position.

The advantage of interface-oriented thinking is that it puts the focus on the role that an object fulfills in a given interaction with other objects, without concern for any other roles the object may play in other kinds of interactions. It also allows testing to focus on scenarios that are relevant to a role (and to mock or fake roles in a test scenario).

joel.neely