Take the 2-minute tour ×

I have seen this mentioned a few times and I am not totally clear on what it means. When and why would you do this?

I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly.

Is it just so if you were to do:

IInterface classRef = new ObjectWhatever()

You could use any class that implements IInterface? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed expect for it implementing IInterface. I cannot think how often you would need to do that... (Also, how could you write a method that takes in a object that implements an interface? Is that possible?)

Sorry if I completely missed the point.

Additional questions:

  • does using an Interface hit performance?
  • if so how much?
  • how can you avoid it without having to maintain two bits of code?
share|improve this question
If you can remember and your program needs to be optimal, just before compilation you may wish to swap the Interface declaration for the actual implementation. As using an interface adds a level of indirection which gives a performance hit. Distribute your code programmed to interfaces though... –  Ande Dec 21 '08 at 4:21
@Ande Turner: that's poor advice. 1). "your program needs to be optimal" is not a good reason for swapping out interfaces! Then you say "Distribute your code programmed to interfaces though..." so you are advising that given requirement (1) you then release sub-optimal code?!? –  Mitch Wheat Dec 21 '08 at 4:26
Cheers for the Edit, The title is much better :) –  Damien Dec 21 '08 at 11:50
Most of the answers here aren't quite right. It doesn't mean or even imply "use the interface keyword" at all. An interface is a spec of how to use something--synonymous with the contract (look it up). Separate from that is the implementation, which is how that contract is fulfilled. Program against only the guarantees of the method / type so that, when the method / type is changed in a way that still obeys the contract, it does not break the code using it. –  apollodude217 Apr 27 '12 at 16:34
The fundemental problem with questions like this is that it assumes that "programming to an interface" means "wrap everything in an abstract interface", which is silly if you consider the term predates the concept of Java style abstract interfaces. –  Jonathan Allen Jul 19 '12 at 19:37

23 Answers 23

up vote 722 down vote accepted

There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.

When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a weaker form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.

For example -- say you have a SIM game and have the following classes:

 class HouseFly inherits Insect {
   void FlyAroundYourHead();
   void LandOnThings();

 class Telemarketer inherits Person {
   void CallDuringDinner();
   void ContinueTalkingWhenYouSayNo();

Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.

Let's say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly or a Telemarketer or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?

The key to realize is that both a Telemarketer and HouseFly share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:

 interface IPest {
    void BeAnnoying();

 class HouseFly inherits Insect implements IPest {
   void FlyAroundYourHead();
   void LandOnThings();

   void BeAnnoying() {

 class Telemarketer inherits Person implements IPest {
   void CallDuringDinner();
   void ContinueTalkingWhenYouSayNo();

   void BeAnnoying() {

We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of IPest -- that contract is simple. You just have to BeAnnoying. In this regard, we can model the following:

 class DiningRoom {

   DiningRoom(Person[] diningPeople, IPest[] pests) { ... }

   void ServeDinner() {
     when diningPeople are eating,

       foreach pest in pests

Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the pests array could actually be a Telemarketer object or a HouseFly object.

The ServeDinner method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the IPest interface. In this way, we can easily have both Telemarketers and HouseFlys be annoying in each of their own ways -- we care only that we have something in the DiningRoom object that is a pest, we don't really care what it is and they could have nothing in common with other.

This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies.

share|improve this answer
+1 for the example. Made my day. –  EricSchaefer Dec 21 '08 at 16:52
That's the best explanation I've heard. –  Tester101 Jan 8 '09 at 21:41
This is an excellent example - it really helped me understand why you'd code to an interface rather than an implementation. It's something I've struggled with for ages and it's only this example that's really made me understand properly. So thankyou. –  John Gallagher Jul 2 '09 at 13:40
+1 For the Telemarketer implementing the IPest interface. Classic! –  FreeAsInBeer Apr 7 '11 at 19:09
I wish school/college textbooks were written by people like you @PeterMeyer. –  avlesh Nov 28 '11 at 17:44

The specific example I used to give to students is that they should write

List myList = new ArrayList(); // programming to the List interface

instead of

ArrayList myList = new ArrayList(); // this is bad

These look exactly the same in a short program, but if you go on to use myList 100 times in your program you can start to see a difference. The first declaration ensures that you only call methods on myList that are defined by the List interface (so no ArrayList specific methods). If you've programmed to the interface this way, later on you can decide that you really need

List myList = new TreeList();

and you only have to change your code in that one spot. You already know that the rest of your code doesn't do anything that will be broken by changing the implementation because you programmed to the interface.

share|improve this answer
Actually I may be wrong, sorry... –  Ed S. Dec 21 '08 at 1:39
In Java it's an interface. But you have the idea, you want whatever the interface is, not a specific implementation. –  Bill the Lizard Dec 21 '08 at 1:41
@EdS. Most answers to this question have the common misconception that "programming to an interface" means use the interface language construct; which is totally wrong! This is the first answer I've seen that correctly illustrates that "programming to an interface" means: don't unnecessarily bind your 'client code' to concrete/specific subclass implementations because if you later decide to change it use a different implementation, you have a lot more work undoing all the unnecessary bindings. I.e. program to/bind to things without implementation details. E.g. Abstract base classes.;) –  Craig Young Nov 22 '11 at 20:45
+1 to @CraigYoung comment. Inheritance is intended to enable one to express all sub-classes in the same way. This is the fundamental description of an interface. –  radarbob May 23 '13 at 16:04
I totally think THIS COMMENT is the RIGHT ANSWER to the question. How to group different objects by using interface (as explained by Peter Meyer above) is a basic thing. The key concept to answer the title question is the interchangeability of the classes implementing the interface, making changes to your code easier. The lower the level of coupling between your modules/classes is, the easier it is to make changes. It's to bad those people who just go for the top-voted answer and think they understood, will never have the chance to realize, they didn't get an answer they were looking for. –  Kovács Imre Dec 9 '13 at 12:29

You should look into Inversion of Control:

In such a scenario, you wouldn't write this:

IInterface classRef = new ObjectWhatever();

You would write something like this:

IInterface classRef = container.Resolve<IInterface>();

This would go into a rule-based setup in the container object, and construct the actual object for you, which could be ObjectWhatever. The important thing is that you could replace this rule with something that used another type of object altogether, and your code would still work.

If we leave IoC off the table, you can write code that knows that it can talk to an object that does something specific, but not which type of object or how it does it.

This would come in handy when passing parameters.

As for your parenthesized question "Also, how could you write a method that takes in a object that implements a Interface? Is that possible?", in C# you would simply use the interface type for the parameter type, like this:

public void DoSomethingToAnObject(IInterface whatever) { ... }

this plugs right into the "talk to an object that does something specific". The method defined above knows what to expect from the object, that it implements everything in IInterface, but it doesn't care which type of object it is, only that it adheres to the contract, which is what an interface really is.

For instance, you're probably familiar with calculators and have probably used quite a few in your days, but most of the time they're all different. You, on the other hand, knows how a standard calculator should work, so you're able to use them all, even if you can't use the specific features that each calculator has that none of the other has.

This is the beauty of interfaces. You can write a piece of code, that knows that it will get objects passed to it that it can expect a certain behaviour from. It doesn't care one hoot what kind of object it is, only that it supports the behaviour needed.

Let me give you a concrete example.

We have a custom-built translation system for windows forms. This system loops through controls on a form, and translates text in each. The system knows how to handle basic controls, like the-type-of-control-that-has-a-Text-property, and similar basic stuff, but for anything basic, it falls short.

Now, since controls inherit from pre-defined classes that we have no control over, we could do one of three things:

  1. Build support into our translation system to detect specifically which type of control it is working with, and translate the correct bits (maintenance nightmare)
  2. Build support into base classes (impossible, since all the controls inherit from different pre-defined classes)
  3. Add interface support

So we did nr. 3. All our controls implement ILocalizable, which is an interface that gives us one method, the ability to translate "itself" through a container of translation text/rules. As such, the form doesn't need to know which kind of control it has found, only that it implements the specific interface, and knows that there is a method there it can call to localize the control.

share|improve this answer
Why mentioning IoC in the very beginning as this would only add more confusion. –  Khnle - Kevin Dec 21 '08 at 1:13
Agree, I would say programming against interfaces is just a technique to make IoC easier and reliable. –  terjetyl Dec 21 '08 at 2:36
Thanks! Helped a lot :) –  Damien Dec 21 '08 at 11:58

Using interfaces is a key factor in making your code easily testable in addition to removing unnecessary couplings between your classes. By creating an interface that defines the operations on your class, you allow classes that want to use that functionality the ability to use it without depending on your implementing class directly. If later on you decide to change and use a different implementation, you need only change the part of the code where the implementation is instantiated. The rest of the code need not change because it depends on the interface, not the implementing class.

This is very useful in creating unit tests. In the class under test you have it depend on the interface and inject an instance of the interface into the class (or a factory that allows it to build instances of the interface as needed) via the constructor or a property settor. The class uses the provided (or created) interface in its methods. When you go to write your tests, you can mock or fake the interface and provide an interface that responds with data configured in your unit test. You can do this because your class under test deals only with the interface, not your concrete implementation. Any class implementing the interface, including your mock or fake class, will do.

EDIT: Below is a link to an article where Erich Gamma discusses his quote, "Program to an interface, not an implementation."


share|improve this answer
great interview linj, thanks! –  PawelP Nov 15 '13 at 10:47
Please, read again this interview : Gamma was of course talking about the OO concept of interface, not the JAVA or the C# special kind of class (ISomething). The problem is, most people though he was talking about the keyword, so we now have a lot of uneeded interfaces (ISomething). –  SRO Mar 13 at 12:17

Programming to an interface is saying "I need this functionality and I don't care where it comes from."

Consider (in Java), the List interface versus the ArrayList and LinkedList concrete classes. If all I care about is that I have a data structure containing multiple data items that I should access via iteration, I'd pick List (and that's 99% of the time). If I know that I need constant-time insert/delete from either end of the list, I might pick the LinkedList concrete implementation (or more likely, use the Queue interface). If I know I need random access by index, I'd pick the ArrayList concrete class.

share|improve this answer
totally agree i.e. the independence between what is done vs. how it is done. By partitioning a system along independent components, you end up with a system that it is simple and reusable (see Simple Made Easy by the guy who created Clojure) –  beluchin Dec 29 '13 at 7:56

Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn't even an OOP concept.

What it really means is don't go messing around with the internals of an object or data structure. Use the Abstract Program Interface, or API, to interact with your data. In Java or C# that means using public properties and methods instead of raw field access. For C that means using functions instead of raw pointers.

EDIT: And with databases it means using views and stored procedures instead of direct table access.

share|improve this answer
Best answer. Gamma give a similar explanation here : artima.com/lejava/articles/designprinciples.html (see page 2). He is refering to the OO concept but you are right: it is larger then that. –  SRO Mar 13 at 12:23

If you program in Java, JDBC is a good example. JDBC defines a set of interfaces but says nothing about the implementation. Your applications can be written against this set of interfaces. In theory, you pick some JDBC driver and your application would just work. If you discover there's a faster or "better" or cheaper JDBC driver or for whatever reason, you can again in theory re-configure your property file, and without having to make any change in your application, your application would still work.

share|improve this answer
It's not just useful in case a better driver becomes available, it makes it possible to change database vendors completely. –  Ken Liu Dec 21 '08 at 4:57
+1, JDBC is the example I was going to post. –  Karl Dec 21 '08 at 16:09
JDBC is so bad that it needs replacing. Find another example. –  Joshua Jan 4 '11 at 21:43

It sounds like you understand how interfaces work but are unsure of when to use them and what advantages they offer. Here are a few examples of when an interface would make sense:

// if I want to add search capabilities to my application and support multiple search
// engines such as google, yahoo, live, etc.

interface ISearchProvider
    string Search(string keywords);

then I could create GoogleSearchProvider, YahooSearchProvider, LiveSearchProvider etc.

// if I want to support multiple downloads using different protocols
interface IUrlDownload
    void Download(string url)

// how about an image loader for different kinds of images JPG, GIF, PNG, etc.
interface IImageLoader
    Bitmap LoadImage(string filename)

then create JpegImageLoader, GifImageLoader, PngImageLoader, etc.

Most add-ins and plugin sytems work off interfaces.

Another popular use is for the Repository pattern. Say I want to load a list of zip codes from different sources

interface IZipCodeRepository
    IList<ZipCode> GetZipCodes(string state);

then I could create an XMLZipCodeRepository, SQLZipCodeRepository, CSVZipCodeRepository, etc. For my web applications I often create XML repositories early on so I can get something up and running prior to the Sql Database being ready. Once the database is ready I write an SQLRepository to replace the XML version. The rest of my code remains unchanged since it runs soley off of interfaces.

Methods can accept interfaces such as:

PrintZipCodes(IZipCodeRepository zipCodeRepository, string state)
    foreach (ZipCode zipCode in zipCodeRepository.GetZipCodes(state))
share|improve this answer

Programming to Interfaces is awesome, it promotes loose coupling. As @lassevk mentioned, Inversion of Control is a great use of this.

instead, look into SOLID principals. here is a video series

It goes through a hard coded (strongly coupled example) then looks at interfaces, finally progressing to a IoC/DI tool (NInject)

share|improve this answer
the link is broken –  baskar_p Dec 16 '14 at 6:52
thanks, that is a shame as it was a fun presentation –  dbones Dec 17 '14 at 18:55

In addition to the already selected answer (and the various informative posts here), I would highly recommend grabbing a copy of Head First Design Patterns. It is a very easy read and will answer your question directly, explain why it is important, and show you many programming patterns you can use to make use of that principle (and others).

share|improve this answer
Cheers, Sounds good! –  Damien Jan 9 '09 at 14:24

It makes your code a lot more extensible and easier to maintain when you have sets of similar classes. I am a junior programmer, so I am no expert, but I just finished a project that required something similar.

I work on client side software that talks to a server running a medical device. We are developing a new version of this device that has some new components that the customer must configure at times. There are two types of new components, and they are different, but they are also very similar. Basically, I had to create two config forms, two lists classes, two of everything.

I decided that it would be best to create an abstract base class for each control type that would hold almost all of the real logic, and then derived types to take care of the differences between the two components. However, the base classes would not have been able to perform operations on these components if I had to worry about types all of the time (well, they could have, but there would have been an "if" statement or switch in every method).

I defined a simple interface for these components and all of the base classes talk to this interface. Now when I change something, it pretty much 'just works' everywhere and I have no code duplication.

share|improve this answer

To add to the existing posts, sometimes coding to interfaces helps on large projects when developers work on separate components simultaneously. All you need is to define interfaces upfront and write code to them while other developers write code to the interface you are implementing.

share|improve this answer

A lot of explanation out there, but to make it even more simpler. Take for instance a List. One can implement a list with as:

  1. an internal array
  2. A linked list
  3. other implementation

By building to an interface, say a List. You only code as to definition of List or what List means in reality.

You could use any type of implementation internally say an array implementation. But suppose you wish to change the implementation for some reason say a bug or performance. Then you just have to change the declaration List<String> ls = new ArrayList<String>() to List<String> ls = new LinkedList<String>().

No where else in code, will you have to change anything else; Because everything else was built on definition of List.

share|improve this answer

So, just to get this right, the advantage of a interface is that I can separate the calling of a method from any particular class. Instead creating a instance of the interface, where the implementation is given from whichever class I choose that implements that interface. Thus allowing me to have many classes, which have similar but slightly different functionality and in some cases (the cases related to the intention of the interface) not care which object it is.

For example, I could have a movement interface. A method which makes something 'move' and any object (Person, Car, Cat) that implements the movement interface could be passed in and told to move. Without the method every knowing the type of class it is.

share|improve this answer

It is also good for Unit Testing, you can inject your own classes (that meet the requirements of the interface) into a class that depends on it

share|improve this answer

Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin, and then calls the methods of that interface to communicate with the plugins.

This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.

Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.

You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.

share|improve this answer

C++ explanation.

Think of an interface as your classes public methods.

You then could create a template that 'depends' on these public methods in order to carry out it's own function (it makes function calls defined in the classes public interface). Lets say this template is a container, like a Vector class, and the interface it depends on is a search algorithm.

Any algorithm class that defines the functions/interface Vector makes calls to will satisfy the 'contract' (as someone explained in the original reply). The algorithms don't even need to be of the same base class; the only requirement is that the functions/methods that the Vector depends on (interface) is defined in your algorithm.

The point of all of this is that you could supply any different search algorithm/class just as long as it supplied the interface that Vector depends on (bubble search, sequential search, quick search).

You might also want to design other containers (lists, queues) that would harness the same search algorithm as Vector by having them fulfill the interface/contract that your search algorithms depends on.

This saves time (OOP principle 'code reuse') as you are able to write an algorithm once instead of again and again and again specific to every new object you create without over-complicating the issue with an overgrown inheritance tree.

As for 'missing out' on how things operate; big-time (at least in C++), as this is how most of the Standard TEMPLATE Library's framework operates.

Of course when using inheritance and abstract classes the methodology of programming to an interface changes; but the principle is the same, your public functions/methods are your classes interface.

This is a huge topic and one of the the cornerstone principles of Design Patterns.

share|improve this answer

In Java these concrete classes all implement the CharSequence interface:

CharBuffer, String, StringBuffer, StringBuilder

These concrete classes do not have a common parent class other than Object, so there is nothing that relates them, other than the fact they each have something to do with arrays of characters, representing such, or manipulating such. For instance, the characters of String cannot be changed once a String object is instantiated, whereas the characters of StringBuffer or StringBuilder can be edited.

Yet each one of these classes is capable of suitably implementing the CharSequence interface methods:

char charAt(int index)
int length()
CharSequence subSequence(int start, int end)
String toString()

In some cases Java class library classes that used to accept String have been revised to now accept the CharSequence interface. So if you have an instance of StringBuilder, instead of extracting a String object (which means instantiating a new object instance), can instead just pass the StringBuilder itself as it implements the CharSequence interface.

The Appendable interface that some classes implement has much the same kind of benefit for any situation where characters can be appended to an instance of the underlying concrete class object instance. All of these concrete classes implement the Appendable interface:

BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer

share|improve this answer
It's too bad interfaces like CharSequence are so anemic. I wish Java and .NET had allowed interfaces to have default implementation, so that people wouldn't pare down interfaces purely for the purpose of minimizing boilerplate code. Given any legitimate CharSequence implementation one could emulate most of the functions of String using only the above four methods, but many implementations could perform those functions much more efficiently in other ways. Unfortunately, even if a particular implementation of CharSequence holds everything in a single char[] and could perform many... –  supercat Oct 18 '14 at 16:58
...operations like indexOf quickly, there's no way that a caller who isn't familiar with a particular implementation of CharSequence could ask it to do so rather than having to use charAt to examine each individual character. –  supercat Oct 18 '14 at 17:00

In simple terms... If I'm writing a new class Swimmer to add the functionality swim() and need to use an object of class say Dog, and this Dog class implements interface Animal which declares swim()[To better understand...you may draw a diagram as to what I am talking about]. At the top of the hierarchy(Animal) it's very abstract while at the bottom (Dog) it's very concrete. The way I think about "programming to interfaces" is that, as I write Swimmer class, I want to write my code against the interface that's as far up that hierarchy which in this case is Animal object. An interface is free from implementation details and thus makes your code loosely-coupled. The implementation details can be changed with time, however it would not affect the remaining code since all you are interacting is with the interface and not the implementation. You don't care what the implementation is like...all you know is that there will be a class that would implement the interface.

share|improve this answer

short story:Postman is asked to go home by home and receive the covers contains (letters,documents,cheques,giftcard,application,loveletter) with address written on it to deliver.

Suppose there is no cover and ask post man to go home by home and receive all the things and deliver to other person the postman can get confuse,

so better wrap it with cover(in our story it is interface) then he will do his job fine.

Now postman job is to receive and deliver the covers only..(he dont bothered what is inside in the cover).

Create type of interface not actual type, but implement with actual type.

Create to interface means your components get Fits into the rest of code easily

I give you example.

you have AirPlane interface as below.

interface Airplane{

Suppose you have methods in your Controller class of Planes like

parkPlane(Airplane plane)


servicePlane(Airplane plane)

implemented in your program. It will not BREAK your code. I mean, it need not to change as long as it accepts arguments as AirPlane.

Because it will accept any Airplane despite of actual type, flyer, highflyr, fighter, etc.

Also, in a collection:

List<Airplane> plane; // Will take all your planes.

The following example will clear your understanding.

You have a fighter plane that implements it, so

public class Fighter implements Airplane {

    public void  parkPlane(){
        // Specific implementations for fighter plane to park
    public void  servicePlane(){
        // Specific implementatoins for fighter plane to service.

The same thing for HighFlyer and other clasess:

public class HighFlyer implements Airplane {

    public void  parkPlane(){
        // Specific implementations for HighFlyer plane to park

    public void  servicePlane(){
        // specific implementatoins for HighFlyer plane to service.

Now think your controller classes using AirPlane several times,

Suppose your Controller class is ControlPlane like below,

public Class ControlPlane{ 
 AirPlane plane;
 // so much method with AirPlane reference are used here...

here magic comes as

you may make your new AirPlane type instances as many as you want and you are not changing

code of ControlPlane class.

you can add instance..

JumboJetPlane // implementing AirPlane interface.
AirBus        // implementing AirPlane interface.

you may remove instances.. of previously created types too.

share|improve this answer

Q: - ... "You could use any class that implements interface?"
A: - Yes.

Q: -... "When would you need to do that?"
A: - Each time you need a class(es) that implements interface(s).

Note: we couldn't instantiate an interface not implemented by a class - True.

  • why?
  • because interface has only methods prototypes, not definitions (just functions names, not their logic)

AnIntf anInst = new Aclass();
// we could do this only if Aclass implements AnIntf.
// anInst will have Aclass reference.

Now we could understand what happend if Bclass and Cclass implements same Dintf.

Dintf bInst = new Bclass();  
// now we could call all Dintf functions implemented (defined) in Bclass.

Dintf cInst = new Cclass();  
// now we could call all Dintf functions implemented (defined) in Cclass.

What we have:
same interface prototypes (functions names in interface), and call different implementations.

Prototypes - wikipedia

share|improve this answer

Also I see a lot of good and explanatory answers here, so I want to give my point of view here, including some extra information what I noticed when using this method.

Unit testing

For the last two years, I have written a hobby project and I did not write unit tests for it. After writing about 50K lines I found out it would be really necessary to write unit tests. I did not use interfaces (or very sparingly) ... and when I made my first unit test, I found out it was complicated. Why?

Because I had to make a lot of class instances, used for input as class variables and/or parameters. So the tests look more like integration tests (having to make a complete 'framework' of classes since all was tied together).

Fear of interfaces So I decided to use interfaces. My fear was that I had to implement all functionality everywhere (in all used classes) multiple times. In some way this is true, however, by using inheritance it can be reduced a lot.

Combination of interfaces and inheritance I found out the combination is very good to be used. I give a very simple example.

public interface IPricable
    int Price { get; }

public interface ICar : IPricable

public abstract class Article
    public int Price { get { return ... } }

public class Car : Article, ICar
    // Price does not need to be defined here

This way copying code is not necessary, while still having the benefit of using a car as interface (ICar).

share|improve this answer

Here is a simple example to illustrate when you program a flight booking system.

//This interface is very flexible and abstract
    addPassenger(Plane seat, Ticket ticket); 

//Boeing is implementation of Plane
    addPassenger(Boeing747 seat, EconomyTicket ticket); 
    addPassenger(Cessna, BusinessClass ticket);

    addPassenger(J15, E87687); 
share|improve this answer

protected by Explosion Pills Dec 18 '12 at 22:36


Would you like to answer one of these unanswered questions instead?
