Interfaces

P

Phil D

Hi,

I am new to c# and oop and have a question about interfaces which I hope
someone can help me with.

The book I am using (C# Step by Step) explains how to create and implement
interfaces (in terms of syntax and grammar), but what it doesn't cover is
why I'd use an interface, and the reasons for doing so.

Currently I just can't see what the value of an interface is, or why I'd
ever want to use one.

Could someone either explain this to me simply, or point me to some good
references (web or books) which cover this topic.

Many Thanks

Phil D
 
E

Eddy

An interface is used when there is no default implementation to inherit.
Whereas an abstract class is best used for prividing data and services for
objects in a hierarchical relationship, an interface can be used for
prividing services that "bring together" disparate objects that relate to
one another only through that interface.
A class that implement an interface sings a contract with the compiler that
says "this class will define all the properties and methods specified by the
interface."
Interfaces provide uniform sets of methods and properties for objects of
disparate classes. These methods and properties enable programs to process
the objects of those disparate classes polymorphically.

For example a person and a tree, these objects have nothing in comon, it's
illogical to inherit from a base object. But, both objects have an age. You
can implement this property through an interface and then handle these
objects polymorphically.

Eddy
 
I

irfan

another reason for interfaces is in COM. COM works well
with interfaces.

Also, an interface could be thought of as an entry door
into a huge and large room-like COM Component. You could
have n classes within your COM Component and accessing
them would be beneficial using interfaces.
 
J

Jerry Negrelli

I think that the first time I saw an interface example
that made it all click (one of those AHA! moments) was in
using an ADO.NET driver for MySql.

My base class contained a SqlDbConnection object and
implemented various other System.Data.SqlClient classes.
To allow for run-time switching between SqlServer &
MySql, I was able to change my base class to contain the
standard interfaces (IDbConnection, etc.) rather than
containing specific implementations of that interface.
Then at run time I was able to specify that "this
connection object I've defined is actually a SQL Server
connection." This just scratches the surface, but
hopefully this example gives you some guidance.

JER
 
T

Tobes \(Breath\)

Phil D said:
Currently I just can't see what the value of an interface is, or why I'd
ever want to use one.

I think interfaces give many advantages, but I suppose these become more
visible as your system gets bigger. Just a few I can think of are...

Looser Coupling: You get looser coupling if your classes depend on
interfaces rather than concrete classes (or abstract classes). This way you
can plug/unplug classes and features more easily.
Documentation: You can see what interfaces a class implements to quickly get
an idea of it's responsibilities, rather than having to examine all methods.
Could someone either explain this to me simply, or point me to some good
references (web or books) which cover this topic.

Rober C Martin talks alot obout such things in his series of papers (and
latest book) at:

http://www.objectmentor.com/resources/listArticles?key=topic&topic=Design Principles

Some relevant ones might be:

- The Interface Segregation Principle
- The Dependency Inversion Principle
- The Single Responsibility Principle

HTH

Tobes
 
P

Phil D

Thanks for your replies guys.

I'm not sure I'm any the wiser - but I'll put down what I think & see if I
get shot down in flames.

In Eddy's example of trees and people, I can define an interface (IProp) for
a height and age property and then implement those properties in the Trees &
People classes.

Now if I cast myTree as (IProp) I can only get access to the height and age
properties, and similarly for myPerson.

However, I could just access those properties directly via myTree.Age or
myPerson.Height so I'm not sure what I've gained by using the interface.

Is the purpose of the interface to constrain (force) the developer to
implement methods necessary for other objects, say in an environment where
lots of people are working on different parts of code at once, to ensure the
necessary methods etc are always there? or is it something more than that.

Phil D

ps Apologies if i seem really dense !!
 
K

Kenneth Baltrinic

Here is an example that may help you understand the purpose of interfaces.

I often use interfaces to define a "plug-in" archetecture. If I have a
parent application that I want others to be able to write a module for, I
define an interface, (and provide the neccesary documenation for it). Then
others can develope a module (typically a dll) that provides a publicly
instatiatable class that defines my interface.

I have to provide some mechanism whereby they can "register" their module
with my app so that the app has the information it needs to dynamically load
an instance that public class. Once I load this class and place it in a
variable declared to by of my Interface type, I can used it with confidence
because I know it supports all the members I need in order for it to
interact with my app. Below is a simple inteface that I have used in the
past.

/// <summary>
/// This interface is implemented by any class that acts as the public
interface of a
/// Configuration Application Module. It defines the methods and
properties through which
/// the configuration application will comunicate with the module.
/// </summary>
public interface IConfigAppModule
{
/// <summary>
/// This method must be called after instantiating any new object module
prior to invoking
/// any other members of the object except ModuleName,
GetSupportedFileTypes and
/// GetSupportedNewDocumentTypes.
/// </summary>
/// <param name="Host"></param>
/// <returns>Returns true if the module successfully initializes, false
otherwise. A moduel
/// that returns false should be discarded and not used. A module that
returns false is
/// responsible for notifing the user of any errors encountered.</returns>
bool InitModule(IHostConfigApp Host);

/// <summary>
/// Returns a short human readable name of this module.
/// </summary>
string Name { get; }

/// <summary>
/// Provide the host application with a list of file types that this
module is capable of
/// opening with the Open() method.
/// </summary>
/// <returns>Returns a two dementional array of size [n,1] where n is the
number of file
/// types supported. For each file type x [x,0] is the human description
of the file type
/// and [x,1] is the file extention used by the file type. E.g. [0,0] =
"Text Files"
/// [0,1] = ".txt" </returns>
string[,] GetSupportedFileTypes();

/// <summary>
/// Opens a file of one of the types specified by GetSupportedFileTypes.
/// </summary>
/// <param name="FileName"></param>
/// <returns>Returns true if the document was opened, false
otherwise.</returns>
bool OpenFromFile(string FileName);

/// <summary>
/// Provide the host application with a list of Document types that this
module is capable of
/// opening with the OpenNewDocument() method.
/// </summary>
/// <returns>Returns an array of strings where each string is the display
text of the menu entry
/// (or other control) that the user will select to request a new document
of a supported type.
/// This same string is also passed to OpenNewDocument to indicate the
type of document to open.</returns>
string[] GetSupportedNewDocumentTypes();

/// <summary>
/// Opens a new document of the type specified.
/// </summary>
/// <param name="TypeName">The name of the document type to open as
orriginally provided by
/// GetSupportedNewDocumentTypes().</param>
/// <returns>Returns true a document was opened, false
otherwise.</returns>
bool OpenNewDocument(string TypeName);

}
 
F

Frank Oquendo

Phil said:
However, I could just access those properties directly via myTree.Age
or myPerson.Height so I'm not sure what I've gained by using the
interface.

You've gained the ability to access information from disparate objects
in a uniform fashion. Mind you, that's not reason enough to create and
implement interfaces in your code. There must be a real need for it.

In one real-world example, I used an interface to supply myself with
methods needed to manipulate an aggregation of UI controls. The
interface is implemented by one container or another, and the controls
themselves make no difference to me. That one decision allowed me to
change the look and feel of my application in less than two hours when I
was requested to alter the UI.

I simply created a new container and implemented the interface, mapping
the methods to the underlying controls. The code required to populate
and manipulate those controls never changed.

Someone else mentioned "loose coupling". This is exactly that type of
scenario. Had I coded my application directly into the UI, I would have
faced a massive rewrite (or a cut and paste nightmare at the very
least). By separating the controller from the UI, I gained the ability
to quickly and easily change my application's appearance. Interfaces are
one method of achieving such loose coupling.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
P

Phil D

Many thanks - that makes a lot of sense and I can see how using an interface
is applicable.

Phil D

Kenneth Baltrinic said:
Here is an example that may help you understand the purpose of interfaces.

I often use interfaces to define a "plug-in" archetecture. If I have a
parent application that I want others to be able to write a module for, I
define an interface, (and provide the neccesary documenation for it). Then
others can develope a module (typically a dll) that provides a publicly
instatiatable class that defines my interface.

I have to provide some mechanism whereby they can "register" their module
with my app so that the app has the information it needs to dynamically load
an instance that public class. Once I load this class and place it in a
variable declared to by of my Interface type, I can used it with confidence
because I know it supports all the members I need in order for it to
interact with my app. Below is a simple inteface that I have used in the
past.

/// <summary>
/// This interface is implemented by any class that acts as the public
interface of a
/// Configuration Application Module. It defines the methods and
properties through which
/// the configuration application will comunicate with the module.
/// </summary>
public interface IConfigAppModule
{
/// <summary>
/// This method must be called after instantiating any new object module
prior to invoking
/// any other members of the object except ModuleName,
GetSupportedFileTypes and
/// GetSupportedNewDocumentTypes.
/// </summary>
/// <param name="Host"></param>
/// <returns>Returns true if the module successfully initializes, false
otherwise. A moduel
/// that returns false should be discarded and not used. A module that
returns false is
/// responsible for notifing the user of any errors encountered.</return s>
bool InitModule(IHostConfigApp Host);

/// <summary>
/// Returns a short human readable name of this module.
/// </summary>
string Name { get; }

/// <summary>
/// Provide the host application with a list of file types that this
module is capable of
/// opening with the Open() method.
/// </summary>
/// <returns>Returns a two dementional array of size [n,1] where n is the
number of file
/// types supported. For each file type x [x,0] is the human description
of the file type
/// and [x,1] is the file extention used by the file type. E.g. [0,0] =
"Text Files"
/// [0,1] = ".txt" </returns>
string[,] GetSupportedFileTypes();

/// <summary>
/// Opens a file of one of the types specified by GetSupportedFileTypes.
/// </summary>
/// <param name="FileName"></param>
/// <returns>Returns true if the document was opened, false
otherwise.</returns>
bool OpenFromFile(string FileName);

/// <summary>
/// Provide the host application with a list of Document types that this
module is capable of
/// opening with the OpenNewDocument() method.
/// </summary>
/// <returns>Returns an array of strings where each string is the display
text of the menu entry
/// (or other control) that the user will select to request a new document
of a supported type.
/// This same string is also passed to OpenNewDocument to indicate the
type of document to open.</returns>
string[] GetSupportedNewDocumentTypes();

/// <summary>
/// Opens a new document of the type specified.
/// </summary>
/// <param name="TypeName">The name of the document type to open as
orriginally provided by
/// GetSupportedNewDocumentTypes().</param>
/// <returns>Returns true a document was opened, false
otherwise.</returns>
bool OpenNewDocument(string TypeName);

}


Phil D said:
Hi,

I am new to c# and oop and have a question about interfaces which I hope
someone can help me with.

The book I am using (C# Step by Step) explains how to create and implement
interfaces (in terms of syntax and grammar), but what it doesn't cover is
why I'd use an interface, and the reasons for doing so.

Currently I just can't see what the value of an interface is, or why I'd
ever want to use one.

Could someone either explain this to me simply, or point me to some good
references (web or books) which cover this topic.

Many Thanks

Phil D
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top