Click to See Complete Forum and Search --> : Q about interfaces
meshman
July 26th, 2008, 11:35 AM
I guess my question is why. I've been reading an article on it and they give this simple example:
public interface IPencil
{
void Write();
bool IsSharp { get; }
}
public interface IPencilSharpener
{
void Sharpen(IPencil pencil);
}
Then he explains that if this was just a class and wanted to change the Write() function to 'Write(string Message)' that it would break code inheriting the class. That's cool I get that. So to get around the problem he suggests adding this to the class (but not the interface):
public string Message
{
get { return m_message; }
set { m_message = value; }
}
Ok, I get that, the Write() function declaration never changes but why use an interface in the first place? Couldn't I just add the above code to the class, not use the interface at all and solve the problem anyway? The above, whether using an interface or not appears completely and functionally identical. Or what did I miss?
Also, aren't interface declarations supposed to exactly match that of the class its based on? Wouldn't adding a public member to the class and not the interface break that model?
I'm not criticising, just asking... :)
Thanks!
Ref: (http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_interrfaces03052006095933AM/csharp_interrfaces.aspx?ArticleID=cd6a6952-530a-4250-a6d7-54717ef3b345)
darwen
July 26th, 2008, 04:00 PM
Also, aren't interface declarations supposed to exactly match that of the class its based on? Wouldn't adding a public member to the class and not the interface break that model?
No and no. Infact you have the cart before the horse here : you don't base interface definitions on classes, you base classes on interface definitions.
An interface defines methods which the implementation of a class inheriting from the interface must support.
A typical example of this is IEnumerable which is used whenever you do a foreach statement.
Lots and lots of different classes implement IEnumerable so that they can be included in foreach statements. List<>, ArrayList, arrays or even your own classes.
However they all include methods which IEnumerable doesn't include.
An interface is a way of decoupling the interface of a class (i.e. some of its public methods) from the implementation and as such is tremendously useful - even when unit testing (mockups etc).
There is also the constraint in .NET that a class can only inherit from a single concrete class, but multiple interfaces.
Darwen.
meshman
July 26th, 2008, 04:33 PM
No and no. Infact you have the cart before the horse here : you don't base interface definitions on classes, you base classes on interface definitions.
Sorry, I worded that wrong, I do understand it that way.
So are interfaces a general rule of thumb when writing classes or something you'd only use when necessary such as for when multiple inheritence is needed? I'm still a little unclear on why one would use an interface, other than for multiple inheritence.
Thanks for the reply!
darwen
July 26th, 2008, 04:54 PM
Inheritance denotes an 'is kind of' relationship e.g. a sofa is a kind of chair, a stool is a kind of chair so a sofa class would derive from a chair class etc etc
An interface denotes a 'can do to myself' representation. e.g. a chair can move itself if it's powered so you could have an interface IMoveable with method Move which a PoweredWheelChair class would implement, but not a sofa or a stool. Sofas and stools can not move themselves - they have to be moved by an external force. I.e. movement is something done to a sofa or a stool (or even a PoweredWheelChair) but a PoweredWheelChair can move itself.
That's why you implement interfaces and inherit from classes.
Darwen.
meshman
July 28th, 2008, 08:49 AM
Cool, thanks for the replies!
JonnyPoet
July 29th, 2008, 06:37 AM
Hi friends !
There I'm missing two very helpful things to understand why to use interfaces instead of inheritance
The first is a very simple one. For getting the point look at the foreach statement and how it works. You can use foreach with any class which implements the IEnumerable interface as we all know. This techniques, and there are a huge amount of usage like this, is only possible with usage of interfaces. Someone has created the foreach loop command originally and he could only get this working if he is sure thats someone who wants to use it has the correct methods built into that class which should work together with foreach. Interfaces are a contract between codeparts. is says to you: If your code implements this interface and all its methods methods, events, properties... whatecver the interface includes, then it will work together with the already existing code.
So you may also have ICompare for comparing classes which may be usefull in sorting mechanism and lots of others.
How would you asure at compiletime to know if your classes will work together with methods which can handle all classes you can think of. -> use interfaces. You acannot inherit from class A and class B and class C
where A is the really baseclass and B is a baseclass for sorting and C is a baseclass for formatting... but you can inherit from your baseclase and setting contracts like IEnumerable, ICompereable, IDisposeable and others. Any you are able to defibe your owns as you want.
The second very important point is re-useability of code. Example: I have a big database soliution which was needed to change from and ACCESS mdb to SQL 2008 server. Ok The databaselayer was connected to the application by interface so it was easy to exactly know which methods are needed to be built in which format in the new SQL Datalayer. IF this wouldn't have been done that way, it would have needed lots of time to invest to study the whole access datalayer classes and where they are connected to the application. Here are interfaces working like an exact border in a program
cjard
July 29th, 2008, 12:53 PM
Sorry, I worded that wrong, I do understand it that way.
So are interfaces a general rule of thumb when writing classes or something you'd only use when necessary such as for when multiple inheritence is needed?
They arent for multiple inheritance, and multiple inheritance doesnt really make sense other than from a laziness point of view where "additional functionality is needed, so let's just bang on an inheritor"
I gave an example once of going shopping. We need to carry the products in something, so let's just make Shopper inherit from Basket. Cool. Now we need the products to be paid for. Let's jsut make Shopper inherit from Bank. Now we need to get the products home quiickly. Let's make Shopper inherit from Car
MI is not available in a lot of languages because of abuse such as this.
When we talk about interfaces, we are really talking about a type-safe system where the compiler and the runtime checks that something is possible to do before it is done. This is why interfaces often take the form of adjectives, because they describe something about the object.
Taking IEnumerabe, this means "able to be enumerated" which is basically saying that when presented with a situation where enumerating is required, this object will behave to spec.
When an object implements an interface, it is basically passing an exam, gaining a certificate if you like, as to how it can behave. The compiler will check the credential before allowing code that calls on the implementor's expertise.
Picture a vehicle situation. You, as a Driver can potentially drive any kind of IDrivable object. Car, Plane, Bus, Boat all implement IDrivable and Driver.Drive(IDrivable vehicle) means someone can invent a new type of vehicle and you can drive it.. You dont know what the new vehicle is when you write the program, but a plugin developer comes along later and makes a new IDrivable, that obeys the laws laid out in the interface, and your Driver can drive it..
Similarly, when one of your classes implements IEnumerable, then c# will be able to enumerate it. MS didnt know what you would write, but the interface system allows you to prove that your class can behave itself in a certain situation.
This is very different from inheritance because there isnt a concept of "is-a" here. A Bus is not a Car, but both can behave as IDrivable. Interfaces thus allow us to prove a "can behave like a" without needing to be "is a"
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.