Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why use an interface? 4

Status
Not open for further replies.

timmoser

Programmer
Aug 31, 2002
41
US
I'm having a hard time proving the value in creating and using interfaces. I thought maybe if my derived classes all had the same base class or interface in this case, I could cast between them like so...

Code:
class TestInterface{
  [STAThread]
  static void Main(string[] args){
    Queen queen = new Queen();
    King king = new King();
    Queen Newqueen = (Queen)king;
    Console.WriteLine(Newqueen.zz);
    King Newking = (King)queen;
    Console.WriteLine(Newking.yy);
  }
}

interface IPiece{
  string a();
  string bb{
    get;
  }
  string cc{
    set;
  }
}

class King:IPiece{
  public string a(){
    return null;
  }
  public string bb{
    get{return null;}
  }
  public string cc{
    set{}
  }
  public string yy{
    get{return "ee";}
  }
}

class Queen:IPiece{
  public string a(){
    return null;
  }
  public string bb{
    get{return null;}
  }
  public string cc{
    set{}
  }
  public string zz{
    get{return "ww";}		
  }
}

Didn't happen.

Let me know what you think.





 
To use an interface, you may do this:
Code:
IPiece queen = new Queen();
IPiece king = new King();
but not
Code:
IPiece newQueen = (Queen) king;

It looks like c#, and I only know java (and c++).
Your example is very useless and you may not show something useful with that.

If this would be a chess example, IPiece could have a coordinate, and a method
Code:
boolean isValidMove (Field target)
Every figur would implement it in a own way.
One figur would have a method 'jump', not declared by the interface.
Far away from 'IPiece, Queen and King' there is a userinterface, let's call it mouse.
The user takes a figur with the mouse - and we don't know in advance, which he will move.
But we get something like this:
Code:
On MouseRelease ()
{
 // Pseudocode:
  x = m.getX ();
  y = m.getY ();
  x0 = m.PressX ();
  y0 = m.PressY ();
  coord0 = Field.translate (x0, y0);
  coord1 = Field.translate (x, y);
  IPiece figur = Field.getPiece (coord0);
  if (figur.isValidMove (coord1))  
      // ...
}
I had better examples when I was young...
 
If you're using .NET, then interfaces are actually...I wouldn't say "frowned" on, but it is better to use the base class/sub class idea instead.

For instance...

Private MustInherit Class Piece()

End Class

Public Class King()
Inherits Piece

End Class

Public Class Queen()
Inherits Piece

End Class

You still all the common stuff in the Piece class, then have the specific items to the chess pieces in the sub classes.

Could you do this with interfaces? Yes...but remember, interfaces were big with VB6.0 because they didn't have true inheritance. There still are valid times where interfaces should be used, but and MSDN article I read recently suggested there were only about 3 or 4...all other scenarios, using base/sub classes was preferred.

hth

D'Arcy
 
Wow, with all the interfaces MS provides with .Net I thought they were pushing us to them. I have no problem avoiding them, I couldn't see the value of an interface if the can't contain code. Thanks for you help.
 
Don't have much .NET exposure, but in Java an interface can allow you to obtain a kind of multiple inheritance, which is not possible just using subclassing. So for example, you can implement Runnable and have a Thread run your class, without actually having to make your class a subclass of Thread.
 
You can do the same thing with .NET. In fact, there are alot of interfaces built into the framework.

But MS also suggests using interfaces where inheritance isn't feasable, or if the objects behind the interface are drastically different. If inheritance can be accomplished (like in Tim's chess piece example), then its better to go that route.

D
 
There is another very important usage of interfaces from arcitecture perspective (at lease in Java). Interface is something that you can expose and follow without knowing a true implementation behind the interface. It also allows to provide multiple interfaces (access types) to different users(applications) from potentially the same object.

For instance you can have administrative interface and user interface to the account. Admin can freeze an account, while user can only add or get money from it.

Good luck

Leo
 
just learning OOP, and web services....

getting my head round most of OOP but interfaces, i think i understand the theory, but i am stuck as to seeing the use i can make of them..
then again, am not very good at analysing OOP implementation yet...

maybe one day i'll be a worthwhile programmer..

if anyone knows of a goood site where how to analyse needs and schematise OOP is explained, they'll save me hours of head-against-wall-ness

lol
 
Consider a computer. Consider two companies who make computers back in the 70's and 80's. One named IBM and one named Apple.

One manufacturer decided to go with the concept of interfaces, and allow multiple manufacturers to implement those interfaces while making computers. The other manufacturer decided not to do that.

Which type of computer are you reading this post with?

This is not a perfect metaphor, but I think it illustrates the point. Keeping with that same vein:

A mouse has an interface, IMouse. IMouse has:

.Cord
.Buttons[]
.MovementIndicator

.MovementIndicator can be a ball or lately, they have become optical sensors, which are far superior. Nothing had to change on the computer, though, because the mouse still implements the same interface. The computer doesn't want to know how the mouse comes up with its output. Why should it care? All it wants to know is how far to move that cursor... past that... who cares.

USB is another beautiful example of an interface. Now, pretty much any peripheral you buy comes with a USB plug. The computer accepts a plug that is formed in a particular way. It doesn't care WHAT is plugged into that slot... only that it is so wide by so tall.

Interfaces are the best thing to happen to programming since the object. It has spawned an entirely new way of thinking about the resuseability of code. It makes possible (or actually, better) concepts such as SOA (Service Oriented Architecture) to use a current "buzz" word.

This is one of the best books I have read in years. Juval Lowy is just a phenom. It goes way beyond simple interface use... he spends some time there, but then moves on to more serious component oriented topics such as security and remoting. It's just a great great book.


If you check this webpage, they have the first chapter of his book available for download. I highly recommend it.

Oh yea, and performance doesn't matter. Memory and processing power is cheap. Maintainability, scalability, and reuseability are the keys to good systems. ;-)

-p

penny.gif
penny.gif

The answer to getting answered -- faq855-2992
 
Timmoser,
I'll take a stab at explaining the real benefit of interface usage. Bear with my lengthy explanation, I once was in your shoe and I understand the problem you are facing.

When I first ventured into the realm of Object Oriented Programming (OOP), I questioned the purpose of interfaces to many hard-core oo engineers. Out of everyone I had asked the similar question to, only one was able to steer me in the right direction. From there, I took it to the playing fields.

So why was'nt I comftable with the previous 5 answers? Well, most engineers speak code and not concept. Which is where you're heading. I had to learn conceptual theory before I even started dabbling with code, which was the last thing i ever did.

Diving head first and trying to implement Interfaces without understanding it's power will just lead to confusion and needless complexity. with that said, let's step back and look at what Interfaces provide first:

Benefits of Interface usage:
----------------------------
1. Dependency Firewall -
Interfaces break dependencies between two collobrating objects.

2. Pluggability - Interchangable objects in a system. Ex: this is how adobe photoshop plugins work.

2. Ploymorphic Behavior -
Pluggable objects all have the exact same methods, but each objects provides different behavior.






Breaking Dependency Firewalls:
---------------------------------------------------------

Let's tackle the first concept of Dependency Firewalls. Dependencies are created when one object interacts with another. Look at this diagram:

[Switch]----------->[LightBulb]

Two objects in a dependency. A Switch object is able to control a LightBulb. Whats wrong with this design? Everything.!! The main goal of oo is reusability and adapting to change. This design is bad because:

1. I have tied 2 concrete objects together very tightly. Switch is highly dependent upon LightBulb.

2. If Switch needs to interact with an Alarm, the code in Switch will need to be modified, else it breaks.

3 months from now your boss says that the lightbulb is to be replaced with an Alarm, make it happen. You're faced with adding some "if...then" code to the Switch to recognize not only a LightBulb, but also an Alarm.

Not only that but, LightBulb and Alarm might have different methods to turn itself on and off. Ex: LightBulb.TurnOn() and Alarm.MakeNoide();


Do you see where I am headed? Everytime a new object comes along, [Switch] has to be edited. [Switch] is the client, it should never have to change. It changes because of the tight dependency in the infastructure and no formal interface standards. Switch now needs to support specialed code to handle:

LightBulb.TurnOn()
Alarm.MakeNoide();

Break dependencies with Interfaces Firewalls:

On(); / Off();
[Switch]---->[ISwitchableDevice]<-----[LightBulb]

We have now broken the tight coupling with an Interface in the middle. Now a Switch can control any Switchable Device that is capable of being turned on/off.

Basically, anytime you have 2 objects referring to each other in a very concrete manner, break it with an Interface firewall in the middle and give the Interface firewall standard interface methods to use. It's a good principal to follow which leads to more robust and extensible software designs. That takes care of breaking dependencies.






Pluggable modules:
------------------------------------------------------------------------------
Now let's talk about how Interfaces support pluggability and polymorphic behavior. Let's look at the diagram again.

On(); / Off();
[Switch]---->[ISwitchableDevice]<-----[Alarm]

Notice anything? I have replaced the LightBulb with an Alarm device. There is a firewall in the middle so the [Switch] never cares what occurs on the other side. It simply sends the same on() or off() message across.

I can now write new objects that are switchable and simply plug them in on the other side of the firewall [as needed] and yet, Switch still does not care or for that matter does not know whats happening on the other side.
Thats the pluggablity value you get. Switch only expects that the pluggable objects have on() and off() behavior because those are the methods it's calling.






Polymorphism:
------------------
Now the Polymorphism comes into play. An interface acts sort of like a contract that other objects must follow if they want to be treated as pluggable on the other side of the firewall. It's a way to set standards for others to follow.

In this senerio, we are dealing with switchable devices, devices that can be turned either On() or Off(). So I created an appropriate Interface named, ISwitchable.

That Interface specifies a contract that other devices must implement. That contract is what the [Switch] knows about [on() or off()].

So, since devices can turn on and off. The Interface has these blank methods:

Interface ISwitchable {
void On();
void Off();
}


Other switchable objects will provide implemetation for these two behaviors. They will essentially be following a contract by implementing expected behavior.



Conclusion:
-----------------------------------------
Now that we have a used an Interface as a dependency Firewall, it intuitively led to other objects having to follow a contract if they want to be controlled by Switch. This allows for robust code because you are now able to provide pluggable behavior.

Since each plugin object knows how to turn them selves on() and off(), they can do so in their own special ways. Alarms turn on() by emmitting a loud sound...Lights turn on() by illuminating the environment. They each have the same interface methods [on/off] but behave differently under the hood. This is polymorphism in play...


I hoped that helped,
- EdwardJS
JaySmith024@yahoo.com




 
Ex: this is how adobe photoshop plugins work.
That's a good example! Food for thought - what if Adobe had required that all plugins inherit from a PlugIn abstract base class, instead requiring the implementation of an interface?

[pipe]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top