Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I need Interface? [duplicate]

Possible Duplicate:
Interfaces: Why can't I seem to grasp them?
Why would I want to use Interfaces?

I think this question is repeated 1000 times and I'm sorry for asking again. I really looking for a plain simple answer why I explicitly need interface, or if you please explain something I can't achieve without Interface.

If it is multiple inheritance then I would request you to give me one simple example through which I can understand why I need interface.

--Thx in advance.

Note: I'm asking this question in context of .NET(C#) language

Edit1: For now whenever I try to learn Interface my minds tells me --> "buddy you are going to outline someone's body in a white sheet" But you need another white sheet where you have to again draw the outline, draw all body parts fill colors to them to get the real picture". So why I'm wasting first white sheet just to get the outline.

like image 245
Pritam Karmakar Avatar asked Feb 26 '12 09:02

Pritam Karmakar


2 Answers

The easiest way of understanding interfaces is that they allow different objects to expose COMMON functionality. This allows the programmer to write much simplier, shorter code that programs to an interface, then as long as the objects implement that interface it will work.

Database Providers:

There are many different database providers, MySQL, MSSQL, Oracle, etc. However all database objects can DO the same things so you will find many interfaces for database objects. If an object implements IDBConnection then it exposes the methods Open() and Close(). So if I want my program to be database provider agnostic, I program to the interface and not to the specific providers.

IDbConnection connection = GetDatabaseConnectionFromConfig()
connection.Open()
// do stuff
connection.Close()

See by programming to an interface (IDbconnection) I can now SWAP out any data provider in my config but my code stays the exact same. This flexibility can be extremely useful and easy to maintain. The downside to this is that I can only perform 'generic' database operations and may not fully utilize the strength that each particular provider offers so as with everything in programming you have a trade off and you must determine which scenario will benefit you the most.

Collections:

If you notice almost all collections implement this interface called IEnumerable. IEnumerable returns an IEnumerator which has MoveNext(), Current, and Reset(). This allows C# to easily move through your collection. The reason it can do this is since it exposes the IEnumerable interface it KNOWS that the object exposes the methods it needs to go through it. This does two things. 1) foreach loops will now know how to enumerate the collection and 2) you can now apply powerful LINQ exprssions to your collection. Again the reason why interfaces are so useful here is because all collections have something in COMMON, they can be moved through. Each collection may be moved through a different way (linked list vs array) but that is the beauty of interfaces is that the implementation is hidden and irrelevant to the consumer of the interface. MoveNext() gives you the next item in the collection, it doesn't matter HOW it does it. Pretty nice, huh?

Polymorphism

When you are designing your own interfaces you just have to ask yourself one question. What do these things have in common? Once you find all the things that the objects share, you abstract those properties/methods into an interface so that each object can inherit from it. Then you can program against several objects using one interface.

And of course I have to give my favorite C++ polymorphic example, the animals example. All animals share certain characteristics. Lets say they can Move, Speak, and they all have a Name. Since I just identified what all my animals have in common and I can abstract those qualities into the IAnimal interface. Then I create a Bear object, an Owl object, and a Snake object all implementing this interface. The reason why you can store different objects together that implement the same interface is because interfaces represent an IS-A replationship. A bear IS-A animal, an owl IS-A animal, so it makes since that I can collect them all as Animals.

var animals = new IAnimal[] = {new Bear(), new Owl(), new Snake()} // here I can collect different objects in a single collection because they inherit from the same interface

foreach (IAnimal animal in animals) 
{
    Console.WriteLine(animal.Name)
    animal.Speak() // a bear growls, a owl hoots, and a snake hisses
    animal.Move() // bear runs, owl flys, snake slithers
}

You can see that even though these animals perform each action in a different way, I can program against them all in one unified model and this is just one of the many benefits of Interfaces.

So again the most important thing with interfaces is what do objects have in common so that you can program against DIFFERENT objects in the SAME way. Saves time, creates more flexible applications, hides complexity/implementation, models real-world objects / situations, among many other benefits.

Hope this helps.

like image 181
Despertar Avatar answered Nov 03 '22 05:11

Despertar


An interface is a Contract for what the class can do, this means that a single class can fulfill multiple contracts.

An abstract class is a template for how a class should behave, you can only fill out one template per class.

An extended class takes an existing object and adds/changes functionality, you can only extend one parent class per class.

You would use a contract (Interface) if you want to describe how something should act without defining the specific implementation. This contract can be fulfilled by any other class which implements the methods/properties which are defined.

You would use an abstract class if you want to specify part of the functionality up front and then add onto it.

EDIT: Consider this:

You have an application which needs to store some data Say EntityA but you may have multiple ways in which you can store data (eg xml, SQL database, CSV ect). You could create a class for each of these different methods to store EntityA. but when you wanted to change method you would need to explicitly specify the type you want right there.

ie

public class DoStuffWithEntityA{
   public void DoStuffAndStoreAsXml(EntityA entity){ /*Logic*/}
   public void DoStuffAndStoreAsCsv(EntityA entity){ /*Logic*/}
   public void DoStuffAndStoreInDatabase(EntityA entity){ /*Logic*/}
}

prehaps a better way here is to use an interface which describes in general what something that stores EntityA would look like.

eg

public interface IStoreEntityA{
    void Store(EnitityA entity);
}

then you could just say that you want something that stores EntityA in your code

public class DoStuffWithEntityA{
    private IStoreEntityA _entityAStorer;
    public DoStuffWithEntityA(IStoreEntityA howIStoreEntityA){ _entityAStorer = howIStoreEntityA;}
    public void DoStuff(EntityA entity)
    {
        //Do Stuff
        _entityAStorer.Store(entity);
    }
}

This means your logic isnt tightly coupled to the way you store EntityA

like image 6
Not loved Avatar answered Nov 03 '22 03:11

Not loved