When should one use interfaces?

In languages such as Java and C# interfaces provide a means for a class to be have in a polymorphic manner. That is to say a class can satisfy more than one contract - it can behave as multiple different types, a class of one type can be substituted for another. In other languages this can also be provided by multiple inheritance, but there are various disadvantages to this approach. However, having a class behave as more than one type is not the most common motivation for using interfaces.

By programming to interfaces instead of classes you can also decouple your program from specific implementations. This makes it much easier to substitute one class implementation for another. This is particularly useful when writing unit tests where you may wish to swap some heavyweight class implementation with a lightweight mock object. If your program only expects an interface type, and both the heavyweight object and mock object implement said interface, then they are very easy to substitute.

Also, consider a simple Java example where I say have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:

public interface PageDatasource {
    public List<Page> getPages();
}

And use it like so:

PageDatasource datasource = // insert concrete PageDatasource implementation here
List<Pages> pages = datasource.getPages();
display(pages);

I can then write separate database and XML implementations that adhere to this interface:

public class DatabasePageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // Database specific code
    }
}

public class XmlPageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // XML specific code
    }
}

Because I used an interface I can now use either implementation - Database or XML - interchangeably without having to change the parts of my program that ask for the page data. The XML and Database implementations likely do completely different things but all my program cares about is that the object supplying the page data implements the PageDatasource interface.


Interface Real Life analogy:

Let say you want to Issue a Book from Library. What you will do:
1) Go to Library
2) Find the Book which interests you
3) Select the Book
4) Go to Librarian Desk to request them to Issue the Book.

Now here Librarian is an Interface, which means you are not interested in who the hell is Librarian, you are only interested in that person sitting on Librarian desk(is the person who agreed to a contract to act as Librarian, which means that person agreed to implement all the behaviors of Librarian)

So let say: Behavior of Librarian are:
1) Issue book
2) Re-Issue Book
3) Return Book.
the person who is designated as Librarian (which means agreed to adapt the above three behaviors), must implement the behaviors in his own way.

Let say PersonA wants to play a part of Librarian, then he needs to adapt the above 3 Behaviors. We as Client don't care how he is performing his Librarian behaviors, we are only interested in that personA is Librarian and he abides to perform the Librarian tasks.
Therefore what you will do, is Reference by Interface[go to Librarian Desk(which will leads you to persons acting as Librarian)] and let say in Future one person left the Librarian post, then as client it won't affect you if you have approached the Librarian desk, instead of specific person acting as Librarian.So code to Interface instead of Concreteness is beneficial.

class PersonA implements Librarian {
    public void IssueBook(){...}
    public void ReIssueBook(){...}
    public void ReturnBook(){...}

    //Other person related tasks...
}   

Even as a single developer interfaces can be a very useful tool. Let me try to illustrate with an example.

Let's suppose you're developing a system to manage a library catalog and the library will lend both books and DVDs. You decide to create classes Book and Dvd to model items being lent but now you want to implement polymorphism so that you can deal with items rather than books or DVDs. The question is should Item be an abstract class or an Interface ?

In this instance you probably want to use an abstract class since there is functionality common to both Book and Dvd that you can provide by a parent class, for example checking out or returning an item.

Now let's say you want to implement a persistence mechanism for your library catalog. You've decided you want to store some data in a database, some data in XML files and some data in comma delimited files. So the question now is how can you go about doing this in a polymorphic way that allows you to deal with a general persistence API ?

In this case you should probably define an Interface that can be implemented by each of your classes providing the database, XML and comma delimited persistence since each of these persistence mechanisms provides similar features i.e. storing and retrieving data, but each will be implemented very differently. This will allow you to easily change which persistence mechanism you are using without having to make lots of changes to the code that uses the persistence mechanism.


The reason interfaces exist is due to the 2 principle concepts of OOP, which is "identity" and "functionality"

Classes have functionality and an identity. With inheritance, objects instantiated can have a lot of functionality and multiple identities.

Interfaces are an identity without functionality. The functionality will be provided by the class instantiated.

The third form, a "mixin" is functionality without identity. Programming languages like ruby provide this third form of inheritance.

How you use an interface differs by the context of your programming language and your circumstances, but just remember, interfaces are used to define identities which are enforced onto objects.


Interfaces help to clarify the distinction between different functional units. One unit depends on another unit to do something, not to be something. As long as that other can do what's stipulated in the interface (think contract), then it can be anything behind the scenes.

For example, I have a entry processor that reads entries from one place, and writes them to another place. It doesn't care from what/where, or to what/where. All it cares is that it's getting the entry from some type of reader (using the IReader interface) on once side, and handing them off to some type of writer (using the IWriter interface).

In my first implementation, the IReader implementer gets stuff from a SQL database, and the IWriter implementer posts it via a web service client. However, we'll eventually create other implementers on either end to access other repositories (FTP sites, directories of files on a local network drive, etc.).

All this time the processor in the middle doesn't care and doesn't change. It just talks through those standard interfaces.

Theoretically you could use a base class (preferably an abstract one) instead of an interface, but that's starts to lock your modules more tightly together, which makes your system harder to maintain. Loose coupling really does make your life easier, even if you aren't on a team of programmers. Consider yourself as a different programmer, every time you work on a different part of your system. Each time you revisit a given section, you have to relearn what it does to maintain it. If every piece of your system is tightly coupled with every other piece, then you must maintain a constant, intimate knowledge of the entire system, not just the one piece on which you're working.

There's also the benefit of a single class implementing multiple interfaces, which is somewhat like multiple inheritance. In this situation a single class can perform multiple jobs (which can be argued is not very wise, but at least it's possible). If you chose to use an abstract base class instead of an interface above, then your flexibility is limited.