0

I am trying to learn OOP concept at an advance level. I was reading through the topic interfaces and have a confusion. But first, let me show you what exactly caused this confusion.
I tested this Code Sample. but I am confused with the use of interfaces. After implementing that code, it seems to me that I can call the method DoFirst from class A by simply creating an instance of it. so why use an interface at first place?

Something like this:

A myA = new A();
myA.DoFirst();

and similiarly,

B myB = new B();
myB.DoFirst();

In both the classes, i have to implement a method called 'DoFirst', so what good does interface provided to me?

Can't I just write these methods in different classes myself?

my Second question, say I have an interface that has 5 methods. If a class implements it, and only wants to provide implementation of 3 methods instead of writing code of all 5 methods supplied by the interface. Isn't this useless? why have access methods that i don't want?

can somebody answer these with example (Highly appreciated) please?

Community
  • 1
  • 1
Shezi
  • 1,352
  • 4
  • 27
  • 51
  • 1
    I see one of the benefits of interfaces as allowing mocking of an objects implementation to support writing unit tests for code that has not been written. I also helps teams co-ordinate so if I expect that you will create a object that does X Y and Z I can mock this until you finish your implementation, this allows me to carry on my work until you have finished yours. Also in the second case I would create a different interface for both the 5 methods and 3 methods. There must be a reason to omit some methods right? – TheKingDave Feb 22 '13 at 11:53
  • Using an interface forces you to make sure your class implements all of the interfaces methods – Sayse Feb 22 '13 at 11:54
  • 1
    Take a look at the first answer in your link, it actually answer what you are concerning – cuongle Feb 22 '13 at 11:56
  • 2
    Please ask only one thing at a time. For two question, create two separate SO questions (if they are related, insert links). – O. R. Mapper Feb 22 '13 at 11:57
  • As a bit of an example of when it could be needed, back when i was in university, my assignment was to create a creature to take part in a game. Therefore, my lecturer provided an interface that would make sure the creature I made implemented some methods that his private code would be able to use. – Sayse Feb 22 '13 at 11:57
  • I understand that its stupidity not to implement all methods exposed by interfaces. However, if i were to write another interface , why not write a class that does not implement an interface and has all those 3 methods. This way I won't be bound – Shezi Feb 22 '13 at 11:58
  • athar, if you look in my last comment, I was already bound by another programmers code. The interface allowed me to make sure my code would work in their code without needing to see it – Sayse Feb 22 '13 at 12:00
  • sayse you are right, that creature would have some feature like walk, sleep, eat etc. but say i make a class that doesn't implement an interface and has all these methods like walk, sleep , eat etc? then i make another class, that can only sleep and eat but not walk. then another class that can only sleep but not walk or eat. Interfaces fail in this scenario right? – Shezi Feb 22 '13 at 12:02
  • 1
    Yes but then you could look into `abstract` and `virtual` types, the idea of interfaces is to make sure a class implements all the classes inside it. Referring back to my example again; this would have made the code my class was being used in to crash – Sayse Feb 22 '13 at 12:05
  • 1
    the simplest possible answer: Use an interface when you need to reference code externally that should act differently in each class that implements it. – Nevyn Feb 22 '13 at 12:18

3 Answers3

3

The advantage was already pointed out in the link you provided... Basically you can also write

void DoSomething(IMyInterface obj)
{
    obj.DoFirst();
}

And then send any type of object which implements that interface as a parameter.

A myA = new A();
DoSomething(myA);
B myB = new B();
DoSomething(myB);

The method DoSomethig doesn't care about the object's type, as long as it exposes an interface called IMyInterface.

scripni
  • 2,144
  • 2
  • 19
  • 25
2

Some Real Life examples - also, another way/reason to use interfaces.

In my own code I have an Engine which processes code to produce reports in Excel. In this engine, i had to write the code two different ways, one using the Microsoft Excel Interop, the other using the Open Office Interop. Rather than duplicate my entire engine to work two different ways, or write a lot of if statements in all the actual interop functions, I implemented an interface. Then I declared two classes, each one implementing the interface, but one uses Excel and the other uses open office. Then, in my code, I simple reference the interface and its functions and use a single if statement at the very beginning of the function to tell the interface which class to implement.

public class ExcelEngineInterop : ISSinterface
{ ... }

public class OOEngineInterop : ISSinterface
{ ... }

//cant use two variables with the same name, so use 1 interface reference instead
ISSinterface ssInt;
if(ExcelFlag)
    ssInt = new ExcelEngineInterop();
else
    ssInt = new OOEngineInterop();

//two VERY different functions between Excel and OpenOffice.
ssInt.OpenApp();
ssInt.OpenFile(fileName);

//etc etc and so on

This is the other reason to use an interface. When you need one block of code to act two (or more) different ways depending on some external flag.

Another Example.

There is a top level form with lots of custom user controls under it. The user fires a form level event, like a button click, but depending on which user controls are active and what settings are on them at the time the click happens, the controls themselves need to do something different. Rather than writing what could be a rediculously large number of if statements to make sure each one acts correctly from the top level, just implement an interface on each control, then do something like this:

public ButtonClick(object sender, EventArgs e)
{
    //note: I dont know which of my classes currentrightcontrol belongs to at the moment.
    //      it could be any one of 22 different controls. It must be cast to something
    //      in order to call the ButtonClick method (its actual type is generic "UserControl"

    IMyRunControl ctrl = CurrentRightControl as IMyRunControl;
    ctrl.FormButtonClicked();
}
Nevyn
  • 2,623
  • 4
  • 18
  • 32
  • It is an awesome answer, but again say, you made those two classes without using interfaces. Now using flag and an If condition, could you not have achieved the same result? – Shezi Feb 22 '13 at 12:25
  • actually, you are right.. if i were to do that my way, then it would have been really difficult. you are right in that example. if(ExcelFlag) ExcelEngineInterop ee = new ExcelEngineInterop(); else OOEngineInterop oo = new OOEngineInterop(); THEN I WOULD NEED ANOTHER IF CHECK, if ee==null && oo != null then DO THIS. And this check would go long long way... Am I getting it right Nevyn? – Shezi Feb 22 '13 at 12:30
  • correct. If you had two different classes at that level, you would need that exact same switch, or an isNull check, at EVERY SINGLE PLACE the engine needed to use one of the functions of the classes. Using the interface, I am able to eliminate what ends up being something like 150 if statements from the engine code. This seems insignificant, until you remember the number of loops. I counted an average 3000 operations per run get cut by using the interface =D – Nevyn Feb 22 '13 at 12:57
  • 3000 per run, with (depending on the report) anywhere from 1 to 500 'runs' per report....that makes a pretty significant speed increase. Fewer operations means faster code. Also, when you start getting into things like that, you discover the cost of casting objects (boxing/un-boxing) and other similar things that using an interface can get you away from, or at least greatly reduce. – Nevyn Feb 22 '13 at 12:59
0

C# is a statically typed language (at least unless you explicitly tell it not to be). This means that the compiler uses the type of the variable to know whether the referenced object has the members you are about to use.

The interface, therefore, provides a contract to the compiler (and to other programmers, too) that this class implements that interface. Because interfaces can be shared across classes that don't have a hierarchical relationship, this means that you can define a method that can take an object as an argument by defining that interface in the parameter type.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
  • It would be easier for me to understand if you can support your answer with an example please . – Shezi Feb 22 '13 at 11:56