tags:

views:

1899

answers:

22

Could someone please demystify interfaces for me or point me to some good examples. I keep seeing interfaces popup here and there but i havent ever really been exposed to good explanations of interfaces or when to use them?

I am talking about interfaces in contect to interfaces vs abstract classes

+1  A: 

Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance (which leads to strongly coupled code, instead of loosely coupled which can be achieved through using interfaces).

Interfaces describe the functionality, not the implementation.

Darren Kopp
+26  A: 

The easiest answer is that interfaces define a what your class can do. It's a "contract" that says that your class will be able to do that action.

Public Interface IRollOver
    Sub RollOver()
End Interface

Public Class Dog Implements IRollOver
    Public Sub RollOver() Implements IRollOver.RollOver
        Console.WriteLine("Rolling Over!")
    End Sub
End Class

Public Sub Main()
    Dim d as New Dog()
    Dim ro as IRollOver = TryCast(d, IRollOver)
    If ro isNot Nothing Then
        ro.RollOver()
    End If
End Sub

Basically, you are guaranteeing that the Dog class always has the ability to roll over as long as it continues to implement that Interface. Should cats ever gain the ability to RollOver(), they too could implement that interface, and you can treat both Dogs and Cats homogeneously when asking them to RollOver().

Bob King
Key word: polymorphism.
luke
I find it amusing we both posted at about the same time and both of us used Dogs and Cats as a metaphor.
JoshReedSchramm
I think Dogs and Cats are the defacto demonstration for polymorphism.
Bob King
Nit: it's not a contract. It just mandates that certain methods et al with specific names and signatures will be present in the implementing class. It makes no assertions as to what those methods do though.
Wedge
Wedge, that's still a contract, or at the very least, a part of it.
Derek Park
@Wedge - you are guaranteeing that your class can "handle" those methods and provide those properties. That's all an interface needs to do. If Cat's implementation of "RollOver()" causes it to jump on the couch, it's not the caller's responsibility.
Bob King
Cats are too lazy, they will ignore that interface.
Arnis L.
+11  A: 

Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.

Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.

In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:

public void Paint(Car car, System.Drawing.Color color)...

This would work until your client said "now I want to paint trucks" so you could do this:

public void Paint (Vehicle vehicle, System.Drawing.Color color)...

this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:

public interface IPaintable{
   void Paint(System.Drawing.Color color);
}

...and passed that to your routine:

public void Paint(IPaintable item, System.Drawing.Color color){
   item.Paint(color);
}

Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.

Rob Conery
Best analogy I have seen. Thanks!
Uncle
A: 

Simply put: An interface is a class that methods defined but no implementation in them. In contrast an abstract class has some of the methods implemented but not all.

Spoike
+14  A: 

When you drive a friend's car, you more or less know how to do that. This is because conventional cars all have a very similar interface: steering wheel, pedals, and so forth. Think of this interface as a contract between car manufacturers and drivers. As a driver (the user/client of the interface in software terms), you don't need to learn the particulars of different cars to be able to drive them: e.g., all you need to know is that turning the steering wheel makes the car turn. As a car manufacturer (the provider of an implementation of the interface in software terms) you have a clear idea what your new car should have and how it should behave so that drivers can use them without much extra training. This contract is what people in software design refer to as decoupling (the user from the provider) -- the client code is in terms of using an interface rather than a particular implementation thereof and hence doesn't need to know the details of the objects implementing the interface.

Alexander
+26  A: 

Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me try one here.

Say you have a couple classes called Dog, Cat, and Mouse. Each of these classes is a Pet and in theory you could inherit them all from another class called Pet but here's the problem. Pets in and of themselves don't do anything. You can't go to the store and buy a pet. You can go and buy a dog or a cat but a pet is an abstract concept and not concrete.

So You know pets can do certain things. They can sleep, or eat, etc. So you define an interface called IPet and it looks something like this (C# syntax)

public interface IPet
{
    void Eat(object food);
    void Sleep(int duration);
}

Each of your Dog, Cat, and Mouse classes implement IPet.

public class Dog : IPet

So now each of those classes has to have it's own implementation of Eat and Sleep. Yay you have a contract... Now what's the point.

Next let's say you want to make a new object called PetStore. And this isn't a very good PetStore so they basically just sell you a random pet (yes i know this is a contrived example).

public class PetStore
{
     public static IPet GetRandomPet()
     {    
          //Code to return a random Dog, Cat, or Mouse
     } 
}

IPet myNewRandomPet = PetStore.GetRandomPet();
myNewRandomPet.Sleep(10);

The problem is you don't know what type of pet it will be. Thanks to the interface though you know whatever it is it will Eat and Sleep.

So this answer may not have been helpful at all but the general idea is that interfaces let you do neat stuff like Dependency Injection and Inversion of Control where you can get an object, have a well defined list of stuff that object can do without ever REALLY knowing what the concrete type of that object is.

JoshReedSchramm
+1  A: 

Think of an interface as a contract. When a class implements an interface, it is essentially agreeing to honor the terms of that contract. As a consumer, you only care that the objects you have can perform their contractual duties. Their inner workings and details aren't important.

Kevin Pang
+3  A: 

Interfaces let you code against objects in a generic way. For instance, say you have a method that sends out reports. Now say you have a new requirement that comes in where you need to write a new report. It would be nice if you could reuse the method you already had written right? Interfaces makes that easy:

interface IReport
{
    string RenderReport();
}

class MyNewReport : IReport
{
    public string RenderReport()
    {
        return "Hello World Report!";

    }
}

class AnotherReport : IReport
{
    public string RenderReport()
    {
        return "Another Report!";

    }
}

//This class can process any report that implements IReport!
class ReportEmailer()
{
     public void EmailReport(IReport report)
     {
         Email(report.RenderReport());
     }
}

class MyApp()
{
    void Main()
    {
        //create specific "MyNewReport" report using interface
        IReport newReport = new MyNewReport();

        //create specific "AnotherReport" report using interface
        IReport anotherReport = new AnotherReport();

        ReportEmailer reportEmailer = new ReportEmailer();

        //emailer expects interface
        reportEmailer.EmailReport(newReport);
        reportEmailer.EmailReport(anotherReport);



    }

}
Giovanni Galbo
A: 

Here is a db related example I often use. Let us say you have an object and a container object like an list. Let us assume that sometime you might want to store the objects in a particular sequence. Assume that the sequence is not related to the position in the array but instead that the objects are a subset of a larger set of objects and the sequence position is related to the database sql filtering.

To keep track of your customized sequence positions you could make your object implement a custom interface. The custom interface could mediate the organizational effort required to maintain such sequences.

For example, the sequence you are interested in has nothing to do with primary keys in the records. With the object implementing the interface you could say myObject.next() or myObject.prev().

fooledbyprimes
+5  A: 

This is a rather "long" subject, but let me try to put it simple.

An interface is -as "they name it"- a Contract. But forget about that word.

The best way to understand them is through some sort of pseudo-code example. That's how I understood them long time ago.

Suppose you have an app that processes Messages. A Message contains some stuff, like a subject, a text, etc.

So you write your MessageController to read a database, and extract messages. It's very nice until you suddenly hear that Faxes will be also implemented soon. So you will now have to read "Faxes" and process them as messages!

This could easily turn into a Spagetti code. So what you do instead of having a MessageController than controls "Messages" only, you make it able to work with an interface called IMessage (the I is just common usage, but not required).

Your IMessage interface, contains some basic data you need to make sure that you're able to process the Message as such.

So when you create your EMail, Fax, PhoneCall classes, you make them Implement the Interface called IMessage.

So in your MessageController, you can have a method called like this:

private void ProcessMessage(IMessage oneMessage)
{
    DoSomething();
}

If you had not used Interfaces, you'd have to have:

private void ProcessEmail(Email someEmail);
private void ProcessFax(Fax someFax);
etc.

So, by using a common interface, you just made sure that the ProcessMessage method will be able to work with it, no matter if it was a Fax, an Email a PhoneCall, etc.

Why or how?

Because the interface is a contract that specifies some things you must adhere (or implement) in order to be able to use it. Think of it as a badge. If your object "Fax" doesn't have the IMessage interface, then your ProcessMessage method wouldn't be able to work with that, it will give you an invalid type, because you're passing a Fax to a method that expects an IMessage object.

Do you see the point?

Think of the interface as a "subset" of methods and properties that you will have available, despite the real object type. If the original object (Fax, Email, PhoneCall, etc) implements that interface, you can safety pass it across methods that need that Interface.

There's more magic hidden in there, you can CAST the interfaces back to their original objects:

Fax myFax = (Fax)SomeIMessageThatIReceive;

The ArrayList() in .NET 1.1 had a nice interface called IList. If you had an IList (very "generic") you could transform it into an ArrayList:

ArrayList ar = (ArrayList)SomeIList;

And there are thousands of samples out there in the wild.

Interfaces like ISortable, IComparable, etc., define the methods and properties you must implement in your class in order to achieve that functionality.

To expand our sample, you could have a List<> of Emails, Fax, PhoneCall, all in the same List, if the Type is IMessage, but you couldn't have them all together if the objects were simply Email, Fax, etc.

If you wanted to sort (or enumerate for example) your objects, you'd need them to implement the corresponding interface. In the .NET sample, if you have a list of "Fax" objects and want to be able to sort them by using MyList.Sort(), you need to make your fax class like this:

public class Fax : ISorteable 
{
   //implement the ISorteable stuff here.
}

I hope this gives you a hint. Other users will possibly post other good examples. Good luck! and Embrace the power of INterfaces.

warning: Not everything is good about interfaces, there are some issues with them, OOP purists will start a war on this. I shall remain aside. One drawback of an Interfce (in .NET 2.0 at least) is that you cannot have PRIVATE members, or protected, it must be public. This makes some sense, but sometimes you wish you could simply declare stuff as private or protected.

Martín Marconcini
your code sample ArrayList ar = (ArrayList)SomeIList; is incorrect. You can only cast the IList if it was already an ArrayList. The point of using IList was so I can create my own object implementing IList and pass that to any method that takes an IList without first shoving it into an ArrayList.
Robert Paulson
+1  A: 

Assuming you're referring to interfaces in statically-typed object-oriented languages, the primary use is in asserting that your class follows a particular contract or protocol.

Say you have:

public interface ICommand
{
    void Execute();
}
public class PrintSomething : ICommand
{
    OutputStream Stream { get; set; }
    String Content {get; set;}
    void Execute()
    { 
        Stream.Write(content);
    }
}

Now you have a substitutable command structure. Any instance of a class that implements IExecute can be stored in a list of some sort, say something that implements IEnumerable and you can loop through that and execute each one, knowing that each object will Just Do The Right Thing. You can create a composite command by implementing CompositeCommand which will have its own list of commands to run, or a LoopingCommand to run a set of commands repeatedly, then you'll have most of a simple interpreter.

When you can reduce a set of objects to a behavior that they all have in common, you might have cause to extract an interface. Also, sometimes you can use interfaces to prevent objects from accidentally intruding on the concerns of that class; for example, you may implement an interface that only allows clients to retrieve, rather than change data in your object, and have most objects receive only a reference to the retrieval interface.

Interfaces work best when your interfaces are relatively simple and make few assumptions.

Look up the Liskov subsitution principle to make more sense of this.

Some statically-typed languages like C++ don't support interfaces as a first-class concept, so you create interfaces using pure abstract classes.

Update Since you seem to be asking about abstract classes vs. interfaces, here's my preferred oversimplification:

  • Interfaces define capabilities and features.
  • Abstract classes define core functionality.

Typically, I do an extract interface refactoring before I build an abstract class. I'm more likely to build an abstract class if I think there should be a creational contract (specifically, that a specific type of constructor should always be supported by subclasses). However, I rarely use "pure" abstract classes in C#/java. I'm far more likely to implement a class with at least one method containing meaningful behavior, and use abstract methods to support template methods called by that method. Then the abstract class is a base implementation of a behavior, which all concrete subclasses can take advantage of without having to reimplement.

JasonTrue
A: 

Interfaces require any class that implements them to contain the methods defined in the interface.

The purpose is so that, without having to see the code in a class, you can know if it can be used for a certain task. For example, the Integer class in java implements the comparable interface, so, if you only saw the method header (public class String implements Comparable), you would know that it contains a compareTo() method.

cblades
+2  A: 

OK, so it's about abstract classes vs. interfaces...

Conceptually, abstract classes are there to be used as base classes. Quite often they themselves already provide some basic functionality, and the subclasses have to provide their own implementation of the abstract methods (those are the methods which aren't implemented in the abstract base class).

Interfaces are mostly used for decoupling the client code from the details of a particular implementation. Also, sometimes the ability to switch the implementation without changing the client code makes the client code more generic.

On the technical level, it's harder to draw the line between abstract classes and interfaces, because in some languages (e.g., C++), there's no syntactic difference, or because you could also use abstract classes for the purposes of decoupling or generalization. Using an abstract class as an interface is possible because every base class, by definition, defines an interface that all of its subclasses should honor (i.e., it should be possible to use a subclass instead of a base class).

Alexander
+4  A: 

In addition to the function interfaces have within programming languages, they also are a powerful semantic tool when expressing design ideas to other people.

A code base with well-designed interfaces is suddenly a lot easier to discuss. "Yes, you need a CredentialsManager to register new remote servers." "Pass a PropertyMap to ThingFactory to get a working instance."

Ability to address a complex thing with a single word is pretty useful.

Internet Friend
+3  A: 

Interfaces are also key to polymorphism, one of the "THREE PILLARS OF OOD".

Some people touched on it above, polymorphism just means a given class can take on different "forms". Meaning, if we have two classes, "Dog" and "Cat" and both implement the interface "INeedFreshFoodAndWater" (hehe) - your code can do something like this (pseudocode):

INeedFreshFoodAndWater[] array = new INeedFreshFoodAndWater[];
array.Add(new Dog());
array.Add(new Cat());

foreach(INeedFreshFoodAndWater item in array)
{
   item.Feed();
   item.Water();
}

This is powerful because it allows you to treat different classes of objects abstractly, and allows you to do things like make your objects more loosely coupled, etc.

Sam Schutte
+1  A: 

Simple answer: An interface is a bunch of method signatures (+ return type). When an object says it implements an interface, you know it exposes that set of methods.

David
+1  A: 

One good reason for using an interface vs. an abstract class in Java is that a subclass cannot extend multiple base classes, but it CAN implement multiple interfaces.

Eric Asberry
+1  A: 

Java does not allow multiple inheritance (for very good reasons, look up dreadful diamond) but what if you want to have your class supply several sets of behavior? Say you want anyone who uses it to know it can be serialized, and also that it can paint itself on the screen. the answer is to implement two different interfaces.

Because interfaces contain no implementation of their own and no instance members it is safe to implement several of them in the same class with no ambiguities.

The down side is that you will have to have the implementation in each class separately. So if your hierarchy is simple and there are parts of the implementation that should be the same for all the inheriting classes use an abstract class.

A: 

Like others have said here, interfaces define a contract (how the classes who use the interface will "look") and abstract classes define shared functionality.

Let's see if the code helps:

public interface IReport
{
    void RenderReport(); // this just defines the method prototype
}

public abstract class Reporter
{
    protected void DoSomething()
    {
        // this method is the same for every class that inherits from this class
    }
}

public class ReportViolators : Reporter, IReport
{
    public void RenderReport()
    {
        // some kind of implementation specific to this class
    }
}

public class ClientApp
{
    var violatorsReport = new ReportViolators();

    // the interface method
    violatorsReport.RenderReport();

    // the abstract class method
    violatorsReport.DoSomething();
}
Robert S.
A: 

Interfaces are a way to implement conventions in a way that is still strongly typed and polymorphic.

A good real world example would be IDisposable in .NET. A class that implements the IDisposable interface forces that class to implement the Dispose() method. If the class doesn't implement Dispose() you'll get a compiler error when trying to build. Additionally, this code pattern:

using (DisposableClass myClass = new DisposableClass())
  {
  // code goes here
  }

Will cause myClass.Dispose() to be executed automatically when execution exits the inner block.

However, and this is important, there is no enforcement as to what your Dispose() method should do. You could have your Dispose() method pick random recipes from a file and email them to a distribution list, the compiler doesn't care. The intent of the IDisposable pattern is to make cleaning up resources easier. If instances of a class will hold onto file handles then IDisposable makes it very easy to centralize the deallocation and cleanup code in one spot and to promote a style of use which ensures that deallocation always occurs.

And that's the key to interfaces. They are a way to streamline programming conventions and design patterns. Which, when used correctly, promotes simpler, self-documenting code which is easier to use, easier to maintain, and more correct.

Wedge
+4  A: 

Interfaces are a mecanism to reduce coupling between different disparate parts of a system.

Coming from a .net perspective

  • the interface definition is a list of operations and/or properties
  • interface methods are always public
  • the interface itself doesn't have to be public

When you create a class that implements the interface, you must provide either an explicit or implicit implementation of the methods in the interface.

We also must realize that .net has only single inheritance, so interfaces are a necessity for an object to expose methods to other objects that aren't aware of it's class hierarchy. Sometimes we call this exposing behaviors.

An example that's a little more concrete:

Consider is we have many DTO's (data transfer objects) that have properties for who updated last, and when that was. The problem is that not all the DTO's have this property because it's not always relevant. At the same time we wanted a generic mechanism to guarantee these properties are set if available when submitted to the workflow, but the workflow object should be loosely coupled from the submitted objects. i.e. the submit workflow method shouldn't really know about all the subtleties of each object, and all objects in the workflow aren't necessarily DTO objects.

// first pass - not maintainable
void SubmitToWorkflow(object o, User u)
{
  if( o is MapDTO )
  {
     MapDTO map = (MapDTO)o;
     map.LastUpdated = DateTime.UtcNow;
     map.UpdatedByUser = u.UserID;
  }
  else if( o is PersonDTO )
  {
     PersonDTO person = (PersonDTO)o;
     person .LastUpdated = DateTime.Now; // whoops .. should be UtcNow
     person .UpdatedByUser = u.UserID;
  }
  // whoa - very unmaintainable.

So SubmitToWorkflow must know about each and every object. Additionally, the code is a mess with one massive if/else/switch and is violating the Don't Repeat Yourself (DRY) principle.

// second pass - brittle
void SubmitToWorkflow(object o, User u)
{
  if( o is DTOBase )
  {
     DTOBase dto = (DTOBase)o;
     dto.LastUpdated = DateTime.UtcNow;
     dto.UpdatedByUser = u.UserID;
  }

Slightly better, but still brittle. If we want to submit other type of objects, we need more case statements. etc.

// third pass pass - also brittle
void SubmitToWorkflow(DTOBase dto, User u)
{
  dto.LastUpdated = DateTime.UtcNow;
  dto.UpdatedByUser = u.UserID;

Still brittle, and both methods impose the constraint that all the DTO's have to implement this property which we indicated wasn't universally applicable. We could combat this by writing do-nothing methods, but that smells bad. We don't want classes pretending they support update tracking but don't.

Interfaces to the rescue.

If we define a very simple interface

public interface IUpdateTracked
{
  DateTime LastUpdated { get; set; }
  int UpdatedByUser { get; set; }
}

now any class can implement the interface.

public class SomeDTO : IUpdateTracked
{
  // IUpdateTracked implementation as well as other methods for SomeDTO
}

Now lets change our method to be far more generic, smaller, and more maintainable, and will continue to work no matter how many classes implement the interface (DTO's or otherwise)

void SubmitToWorkflow(object o, User u)
{
  IUpdateTracked updateTracked = o as IUpdateTracked;
  if( updateTracked != null )
  {
     updateTracked.LastUpdated = DateTime.UtcNow;
     updateTracked.UpdatedByUser = u.UserID;
  }
  // ...
  • I'll note the variation void SubmitToWorkflow(IUpdateTracked updateTracked, User u) which would guarantee type safety - the compiler enforces all objects are implicitly convertable to IUpdateTracked, however it doesn't seem as relevant in these circumstances, so let's not get sidetracked. See below for an example that uses interfaces in the method declaration.

In our case we have code generation and it creates these DTO classes from the database definition. The only thing we have to do is create the field name correctly and decorate the class with the interface. We don't even have to implement the properties because the compiler just makes sure that there are properties called LastUpdated and UpdatedByUser.

Maybe you're asking What happens if my database is legacy and that's not possible? You just have to do a little more typing, but another great feature of interfaces is they allow you to create a bridge between the classes. We have LegacyDTO which is an older object having similarly-named fields. We implement the IUpdateTracked interface to provide a bridge to updating different-named properties.

public class LegacyDTO : IUpdateTracked
{ 
    public int LegacyUserID { get; set; }
    public DateTime LastSaved { get; set; }

    public int UpdatedByUser
    {
        get { return LegacyUserID; }
        set { LegacyUserID = value; }
    }
    public DateTime LastUpdated
    {
        get { return LastSaved; }
        set { LastSaved = value; }
    }
}

You might thing Cool, but isn't it confusing having multiple properties? or What happens if there are already those properties but they mean something else? In .net we have the ability to explicitly implement the interface. What this means is that the IUpdateTracked properties will only be visible when we're using a reference to IUpdateTracked.

public class YetAnotherObject : IUpdatable
{ 
    int IUpdatable.UpdatedByUser
    { ... }
    DateTime IUpdatable.LastUpdated
    { ... }

So you can do all sorts of things that decouple the object from methods that consume it. Interfaces are a great way to break the coupling.

There is a lot more to interfaces than just this. This is a real-life example that utilizes one aspect of interface based programming. If I get around to it, I'll try to follow up with Dependency Injection (DI) and more examples.

As I mentioned earlier, and by other responders, you can create methods that take and/or return an interface references rather than a class references. If I needed to find duplicates in a list, I could write a method that takes and returns an IList (an interface defining operations that work on lists) and I'm not constrained to a concrete class.

// decouples the caller and the code as both operate only on IList, and are free to change the concrete objects.
public IList FindDuplicates( IList list )
{
    ArrayList arrayList = new ArrayList();
    // insert code to detect duplicated;
    return arrayList;
}

Versioning caveat

If it's a public interface you are saying I guarantee interface x looks like this! and once you have published the interface, you should never change it. Once consumers start to rely on that interface, you don't want to break their code in the field.

Interfaces versus abstract (base) classes

Abstract classes can provide implementation whereas Interfaces cannot. Abstract classes are in some ways more flexable in the versioning aspect if you follow some guidelines like the NVI (Non-Virtual Interface) pattern.

As mentioned before (in .net) a class can only inherit from a single class, but a class can implement as many interfaces as it likes.

Robert Paulson
This is an impressive answer.
ChaosPandion
A: 

I have had the same problem as you and I find the "contract" explanation a bit confusing.

If you specify that a method takes an IEnumerable interface as an in-parameter you could say that this is a contract specifying that the parameter must be of a type that inherits from the IEnumerable interface and hence supports all methods specified in the IEnumerable interface. The same would be true though if we used an abstract class or a normal class. Any object that inherits from those classes would be ok to pass in as a parameter. You would in any case be able to say that the inherited object supports all public methods in the base class whether the base class is a normal class, an abstract class or an interface.

An abstract class with all abstract methods is basically the same as an interface so you could say an interface is simply a class without implemented methods. You could actually drop interfaces from the language and just use abstract class with only abstract methods instead. I think the reason we separate them is for semantic reasons but for coding reasons I don't see the reason and find it just confusing.

Another suggestion could be to rename the interface to interface class as the interface is just another variation of a class.

In certain languages there are subtle differences that allows a class to inherit only 1 class but multiple interfaces while in others you could have many of both, but that is another issue and not directly related I think

TT