tags:

views:

1538

answers:

19

I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

+1  A: 

There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code. You can also provide an sort of standardized API for simple operations.

For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects. If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.

If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.

Interfaces encourage looser coupling of your code so that you can have greater flexibility.

Douglas Mayle
+2  A: 

Interfaces are absolutely necessary in an object-oriented system that expects to make good use of polymorphism.

A classic example might be IVehicle, which has a Move() method. You could have classes Car, Bike and Tank, which implement IVehicle. They can all Move(), and you could write code that didn't care what kind of vehicle it was dealing with, just so it can Move().

void MoveAVehicle(IVehicle vehicle)
{
    vehicle.Move();
}
Eric Z Beard
That would actually work even without interfaces. (Duck typing.) Interfaces merely makes it possible for you to tell the compiler your intent.
Hugo
Actually, the vehicle doesn't have to be an interface, it could be a base class. Interfaces are more suited for services or similar where you just care about the contract and not the inheritance, so i think polymorphism is actually not the important thing about interfaces.
Hugo
Yep, you're right. But usually there's an interface that defines the superclass' methods. And in a certain sense, an interface is a superclass, just with no implementation.
Eric Z Beard
Why should vehicle be a base class? The only commonality that vehicles have is that they move, there are no implementation commonalities beyond that. You gain no advantage, and many disadvantages, from using a base class in this case.
Wedge
@Wedge - A base class would allow you to provide a default implementation down the road. But yes, you could always implement the base class at a later time if needed.
Cory House
+26  A: 

One specific example: interfaces are a good way of specifying a contract that other people's code must meet.

If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.

Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)

Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.

The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details.

The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.

Stewart Johnson
Interfaces are the "best" solution? What about inheritance? With an interface, you must implement every member in every class that uses it, even if those implementations are the same. With inheritance, the base class can implement common members, while the derived classes only contain custom members
DOK
Inheritance tends to be brittle. If you are violating the "is-a" relationship that is implicit when you extend a superclass, you are asking for trouble down the road.
Revah
Revah: OK, you need to use inheritance correctly. But you have to write (amd maintain) so much more duplicate code with an interface vs. having a single version of the method (where appropriate) in a base class.
DOK
@DOK: you're assuming that it is actually possible to write the implementation in an abstract base class. For the examples I gave that's not even possible -- you have to use an interface.
Stewart Johnson
@DOK, If every class that implemented an interface had the same code in its implementation, then yes, you would probably want to go with inheritance instead. The point of interfaces is that the implementation will probably NOT be the same, but the contract should be.
hmcclungiii
@hmcclungiii, if the classes had the same implementation using generics can also help.
John
A: 

As you noted, interfaces are good for when you want to force someone to make it in a certain format.

Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.

For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I know they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.

Interfaces are rarely used because of this, since usually you can make assumptions or don't really require the data to do what you need to do.

Nazadus
Good point about interfaces being brittle. You can't change them without breaking a lot of stuff.
DOK
A: 

An interface, defines merely the interface. Later, you can define method (on other classes), which accepted interfaces as parameters (or more accurately, object which implement that interface). This way your method can operate on a large variety of objects, whose only commonality is that they implement that interface.

James Curran
A: 

First, they give you an additional layer of abstraction. You can say "For this function, this parameter must be an object that has these methods with these parameters". And you probably want to also set the meaning of these methods, in somehow abstracted terms, yet allowing you to reason about the code. In duck-typed languages you get that for free. No need for explicit, syntax "interfaces". Yet you probably still create a set of conceptual interfaces, something like contracts (like in Design by Contract).

Furthermore, interfaces are sometimes used for less "pure" purposes. In Java, they can be used to emulate multiple inheritance. In C++, you can use them to reduce compile times.

In general, they reduce coupling in your code. That's a good thing.

Your code may also be easier to test this way.

phjr
+4  A: 

Interfaces define contracts, and that's the key word.

You use an interface when you need to define a contract in your program but you don't really care about the rest of the properties of the class that fulfills that contract as long as it does.

So, let's see an example. Suppose you have a method which provides the functionality to sort a list. First thing .. what's a list? Do you really care what elements does it holds in order to sort the list? Your answer should be no... In .NET (for example) you have an interface called IList which defines the operations that a list MUST support so you don't care the actual details underneath the surface.

Back to the example, you don't really know the class of the objects in the list... neither you care. If you can just compare the object you might as well sort them. So you declare a contract:

interface IComparable
{
  // Return -1 if this is less than CompareWith
  // Return 0 if object are equal
  // Return 1 if CompareWith is less than this
  int Compare(object CompareWith);
}

that contract specify that a method which accepts an object and returns an int must be implemented in order to be comparable. Now you have defined an contract and for now on you don't care about the object itself but about the contract so you can just do:

IComparable comp1 = list.GetItem(i) as IComparable;

if (comp1.Compare(list.GetItem(i+1)) < 0)
  swapItem(list,i, i+1)

PS: I know the examples are a bit naive but they are examples ...

Jorge Córdoba
+2  A: 

Interfaces are a form of polymorphism. An example:

Suppose you want to write some logging code. The logging is going to go somewhere (maybe to a file, or a serial port on the device the main code runs on, or to a socket, or thrown away like /dev/null). You don't know where: the user of your logging code needs to be free to determine that. In fact, your logging code doesn't care. It just wants something it can write bytes to.

So, you invent an interface called "something you can write bytes to". The logging code is given an instance of this interface (perhaps at runtime, perhaps it's configured at compile time. It's still polymorphism, just different kinds). You write one or more classes implementing the interface, and you can easily change where logging goes just by changing which one the logging code will use. Someone else can change where logging goes by writing their own implementations of the interface, without changing your code. That's basically what polymorphism amounts to - knowing just enough about an object to use it in a particular way, while allowing it to vary in all the respects you don't need to know about. An interface describes things you need to know.

C's file descriptors are basically an interface "something I can read and/or write bytes from and/or to", and almost every typed language has such interfaces lurking in its standard libraries: streams or whatever. Untyped languages usually have informal types (perhaps called contracts) that represent streams. So in practice you almost never have to actually invent this particular interface yourself: you use what the language gives you.

Logging and streams are just one example - interfaces happen whenever you can describe in abstract terms what an object is supposed to do, but don't want to tie it down to a particular implementation/class/whatever.

Steve Jessop
+5  A: 

One typical example is a plugin architecture. Developer A writes the main app, and wants to make certain that all plugins written by developer B, C and D conform to what his app expects of them.

Treb
A: 

Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.

You could then specify an interface ICollection with the methods add(), remove() and contains().

Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.

jakber
A: 

In .Net, I create base classes and inherit from them when the classes are somehow related. For example, base class Person could be inherited by Employee and Customer. Person might have common properties like address fields, name, telephone, and so forth. Employee might have its own department property. Customer has other exclusive properties.

Since a class can only inherit from one other class in .Net, I use interfaces for additional shared functionality. Sometimes interfaces are shared by classes that are otherwise unrelated. Using an interface creates a contract that developers will know is shared by all of the other classes implementing it. I also forces those classes to implement all of its members.

DOK
+2  A: 

The pedals on a car implement an interface. I'm from the US where we drive on the right side of the road. Our steering wheels are on the left side of the car. The pedals for a manual transmission from left to right are clutch -> brake -> accelerator. When I went to Ireland, the driving is reversed. Cars' steering wheels are on the right and they drive on the left side of the road... but the pedals, ah the pedals... they implemented the same interface... all three pedals were in the same order... so even if the class was different and the network that class operated on was different, i was still comfortable with the pedal interface. My brain was able to call my muscles on this car just like every other car.

Think of the numerous non-programming interfaces we can't live without. Then answer your own question.

So, the US Car and UK Car classes implement the Car interface which has methods for Clutch, Brake and Accelerator, and a SteeringWheelOrientation property? Then, the Clutch, Brake and Accelerator methods are basically identical but their code has to be duplicated in every class that implements Car?
DOK
Well I'm not trying to carry the analogy all the way into a programming one. The OP said he knows what they are just not why to use them. I want to show what an interface might look like in a common real-world item. Sometimes it takes stepping outside our current thoughtworld to grasp a concept.
A: 

In an article in my blog I briefly describe three purposes interfaces have.

Interfaces may have different purposes:

  • Provide different implementations for the same goal. The typical example is a list, which may have different implementations for different performance use cases (LinkedList, ArrayList, etc.).
  • Allow criteria modification. For example, a sort function may accept a Comparable interface in order to provide any kind of sort criteria, based on the same algorithm.
  • Hide implementation details. This also makes it easier for a user to read the comments, since in the body of the interface there are only methods, fields and comments, no long chunks of code to skip.

Here's the article's full text: http://weblogs.manas.com.ar/ary/2007/11/

asterite
A: 

Imagine the following basic interface which defines a basic CRUD mechanism:

interface Storable {
    function create($data);
    function read($id);
    function update($data, $id);
    function delete($id);
}

From this interface, you can tell that any object that implements it, must have functionality to create, read, update and delete data. This could by a database connection, a CSV file reader, and XML file reader, or any other kind of mechanism that might want to use CRUD operations.

Thus, you could now have something like the following:

class Logger {
    Storable storage;

    function Logger(Storable storage) {
        this.storage = storage;
    }

    function writeLogEntry() {
        this.storage.create("I am a log entry");
    }
}

This logger doesn't care if you pass in a database connection, or something that manipulates files on disk. All it needs to know is that it can call create() on it, and it'll work as expected.

The next question to arise from this then is, if databases and CSV files, etc, can all store data, shouldn't they be inherited from a generic Storable object and thus do away with the need for interfaces? The answer to this is no... not every database connection might implement CRUD operations, and the same applies to every file reader.

Interfaces define what the object is capable of doing and how you need to use it... not what it is!

JamShady
A: 

In C# interfaces are also extremely useful for allowing polymorphism for classes that do not share the same base classes. Meaning, since we cannot have multiple inheritance you can use interfaces to allow different types to be used. It's also a way to allow you to expose private members for use without reflection (explicit implementation), so it can be a good way to implement functionality while keeping your object model clean.

For example:

public interface IExample
{
    void Foo();
}

public class Example : IExample
{
    // explicit implementation syntax
    void IExample.Foo() { ... }
}

/* Usage */
Example e = new Example();

e.Foo(); // error, Foo does not exist

((IExample)e).Foo(); // success
justin.m.chase
A: 

Wow what a great community. Thank you so much for your responses!

Yeah, pretty interesting, huh? Thanks for asking such a good question.
DOK
A: 

I think you need to get a good understand of design patterns so see there power.

Check out Head First Design Patterns

Mark Lubin
A: 

There are several more answers to a similar question here: Interface vs Base Class

sgreeve
A: 

The best Java code I have ever seen defined almost all object references as instances of interfaces instead of instances of classes. It is a strong sign of quality code designed for flexibility and change.

dongilmore