473,734 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to understand interfaces

RSH
Hi,

I have been reading on interfaces working on samples I've run across on the
web. For the life of me I cannot seem to grasp them.

It appears to me that interfaces are simply blueprints to a class, that when
implemented, they require the implementing calss to make sure that each of
the properties, functions etc. are handled by the class. (????)

What I am really having a problem with is how they overcome the limitation
of multiple inheritance? It would appear that interfaces simply require that
a class handles a predetermined number of properties events etc. So if I
have a class that implements an interface and I need to add functionality to
that class...I still have to add it to the interface and handle it in the
initial class...this seems redundant to me. Not to mention modifying the
interface to include the new required functionality, now makes all other
classes that implement the interface "break" and now require that I modify
all classes that implement the interface to handle the newly added
functionality.

Now I openly admit I am no OOP guru, and I am simply trying to understand
interfaces...I am certainly not bashing them.

The code below illustrates my initial attempt at understanding
interfaces...pi eced together from a few tutorials on the web.

The classes and intefaces apper below. and the instantiation of the objects
appears at the top...and will probably shed light on my lack of
understanding of interfaces.

The first instantiation illustrates the use of the interfaces:
public partial class _Default : System.Web.UI.P age

{

protected void Page_Load(objec t sender, EventArgs e)

{

IPencil p = new Pencil();

p.Type = "Pencil";

IPencil mp = new MechanicalPenci l();

mp.Type = "MechanicalPenc il";

IPencil pen = new Pen();

pen.Type = "Pen";

PencilSharpener sharpener = new PencilSharpener ();

sharpener.Sharp en(p);

sharpener.Sharp en(mp);

sharpener.Sharp en(pen);

}

Now where I get confused is that I can quite simply get the same results by
bypassing the interfaces and never calling the PencilSharpener class:

protected void Page_Load(objec t sender, EventArgs e)

{

IPencil p = new Pencil();

p.Type = "Pencil";

p.OnSharpened() ;

IPencil mp = new MechanicalPenci l();

mp.Type = "MechanicalPenc il";

IPencil pen = new Pen();

pen.Type = "Pen";

//PencilSharpener sharpener = new PencilSharpener ();

//sharpener.Sharp en(p);

//sharpener.Sharp en(mp);

//sharpener.Sharp en(pen);

}

So this is where my paridigm needs some shifting :-)

Can you please help shed some light on this? Thank you very much!

Ron


// Interfaces +++++++++++++++ +++++++++++++++ +++

//Pencil Interface

public interface IPencil

{

string Type { get; set; }

int CurrentSharpnes s { get; set; }

bool IsSharp { get; }

void Write();

void OnSharpened();

}

//Pencil Sharpener Interface

public interface IPencilSharpene r

{

void Sharpen(IPencil pencil);

}



// Classes +++++++++++++++ +++++++++++++++ +++++++

// Pencil Class

public class Pencil : IPencil

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public Pencil()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set {

m_type = value;

m_message = "This is my " + m_type + " writing away!";

m_sharpenedMess age = "This is one sharp " + m_type + "!";

}

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = value; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

// Function

public void Write()

{

foreach (char c in m_message)

{

if (m_Sharpened == false)

{

if (IsSharp)

{

HttpContext.Cur rent.Response.W rite(c);

}

else

{

HttpContext.Cur rent.Response.W rite("#");

}

}

else

{

HttpContext.Cur rent.Response.W rite(c);

}

m_charsUsed++;

}

HttpContext.Cur rent.Response.W rite("<BR>");

}

// Function

public void OnSharpened()

{

while(this.m_cu rrentSharpness < m_message.Lengt h)

{

m_charsUsed = 0;

m_currentSharpn ess++;

Write();

}

m_Sharpened = true;

m_message = m_sharpenedMess age;

Write();

}

public void Sharpen(IPencil pencil)

{

pencil.OnSharpe ned();

}

}

// Pencil Sharpener Class

public class PencilSharpener : IPencilSharpene r

{

public void Sharpen(IPencil pencil)

{

HttpContext.Cur rent.Response.W rite("<br>Begin sharpening " + pencil.Type +
"...<br>");

pencil.OnSharpe ned();

}

}

// Pen Class

class Pen : IPencil

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public Pen()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set { m_type = value; }

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = 0; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

public void Write()

{

HttpContext.Cur rent.Response.W rite(m_message + "<BR>");

}

// Function

public void OnSharpened()

{

m_Sharpened = true;

m_message = "A Pen cannot be sharpened!.";

Write();

}

}

// Mechanical Pencil Class

class MechanicalPenci l : IPencil, IPencilSharpene r

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public MechanicalPenci l()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set { m_type = value; }

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = value; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

// Function

public void Write()

{

foreach (char c in m_message)

{

if (m_Sharpened == false)

{

if (IsSharp)

{

HttpContext.Cur rent.Response.W rite(c);

}

else

{

HttpContext.Cur rent.Response.W rite("#");

}

}

else

{

HttpContext.Cur rent.Response.W rite(c);

}

m_charsUsed++;

}

HttpContext.Cur rent.Response.W rite("<BR>");

}

// Function

public void OnSharpened()

{

m_Sharpened = true;

m_message = "The Mechanical Pencil is self sharpening.";

Write();

}

public void Sharpen(IPencil pencil)

{

}

}

}


Oct 20 '06
22 2107
I think you get it. The example I like to use when explaining using
interfaces is the media player

public interface IMediaPlayer
{
FastForward();
Rewind()
Play();
Stop();
}

Then you can declare classes like

MP3Player : IMediaPlayer
VideoPlayer : IMediaPlayer

Each class performs the same functions, but would be implemented very
differently. You can have common code that does something like:

IMediaPlayer mp;
string playerType = "mp3"
mp = new MP3Player();
mp.Play();
mp.Stop();

mp = new VideoPlayer();
mp.Play();
mp.Stop();

Imagine interfaces being useful if you were writing a Media player that
plays audio files, video files, DVDs, etc.

Each has the same function, but are implemented differently.

"RSH" wrote:
Thanks all!

This is some really goosd stuff...and thank you Dave for that incredibly
clear explanation!!!!

Dare I post my updated code. I modified it based on my new interpretation
of interfaces.
Any comments or feedback would be greatly appreciated. I'm pretty new at
this stuff :-)

THANKS!

Ron

public partial class _Default : System.Web.UI.P age

{

protected void Page_Load(objec t sender, EventArgs e)

{

IWritingInstrum ent pencil = new Pencil();

pencil.Write();

pencil.IsWritin gPoorly = true;

pencil.IsBroken = true;

IWritingInstrum ent mpencil = new MechanicalPenci l();

mpencil.Write() ;

mpencil.IsWriti ngPoorly = true;

mpencil.IsBroke n = true;

IWritingInstrum ent pen = new Pen();

pen.Write();

pen.IsWritingPo orly = true;

pen.IsBroken = true;

}

// Interfaces +++++++++++++++ +++++++++++++++ +++

//Writing Implement Interface

public interface IRepair

{

bool IsWritingPoorly { get; set; }

void Write();

void Fix();

}

//Is Breakable Interface

public interface IReplace

{

bool IsBroken { get; set; }

void Replace();

}

//Combine Interfaces

public interface IWritingInstrum ent : IRepair, IReplace

{

}

// Classes +++++++++++++++ +++++++++++++++ +++++++

// Pencil Class

public class Pencil : IWritingInstrum ent

{

private string m_message;

private Boolean m_isWritingPoor ly;

private Boolean m_isBroken;

// Constructor

public Pencil()

{

m_isWritingPoor ly = false;

m_isBroken = false;

m_message = "";

}

// Property

public Boolean IsBroken

{

get { return m_isBroken; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Broken...we will
replace it for you...";

Write();

Replace();

m_isBroken = false;

}

}

// Property

public bool IsWritingPoorly

{

get { return m_isWritingPoor ly; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Dull...we will
sharpen it for you...";

Write();

Fix();

m_isWritingPoor ly = false;

}

}

// Function

public void Write()

{

HttpContext.Cur rent.Response.W rite(m_message + "<BR>");

}

// Function

public void Fix()

{

m_message = "The " + this.GetType(). Name + " was sharpened and is now
working great!<br>";

Write();

}

public void Replace()

{

m_message = "The " + this.GetType(). Name + " was replaced.<br>";

Write();

}

}

// Pen Class

public class Pen : IWritingInstrum ent

{

private string m_message;

private Boolean m_isWritingPoor ly;

private Boolean m_isBroken;

// Constructor

public Pen()

{

m_isWritingPoor ly = false;

m_isBroken = false;

m_message = "";

}

// Property

public Boolean IsBroken

{

get { return m_isBroken; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Broken...we will
replace it for you...";

Write();

Replace();

m_isBroken = false;

}

}

// Property

public bool IsWritingPoorly

{

get { return m_isWritingPoor ly; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be out of ink...we
will refill it for you...";

Write();

Fix();

m_isWritingPoor ly = false;

}

}

// Function

public void Write()

{

HttpContext.Cur rent.Response.W rite(m_message + "<BR>");

}

// Function

public void Fix()

{

m_message = "The " + this.GetType(). Name + " was refilled and is now working
great!<br>";

Write();
Oct 20 '06 #11
RSH
Great...now on to Delegates!!!!

Thanks everyone!
Ron

"RSH" <wa************ *@yahoo.comwrot e in message
news:OX******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi,

I have been reading on interfaces working on samples I've run across on
the web. For the life of me I cannot seem to grasp them.

It appears to me that interfaces are simply blueprints to a class, that
when implemented, they require the implementing calss to make sure that
each of the properties, functions etc. are handled by the class. (????)

What I am really having a problem with is how they overcome the limitation
of multiple inheritance? It would appear that interfaces simply require
that a class handles a predetermined number of properties events etc. So
if I have a class that implements an interface and I need to add
functionality to that class...I still have to add it to the interface and
handle it in the initial class...this seems redundant to me. Not to
mention modifying the interface to include the new required functionality,
now makes all other classes that implement the interface "break" and now
require that I modify all classes that implement the interface to handle
the newly added functionality.

Now I openly admit I am no OOP guru, and I am simply trying to understand
interfaces...I am certainly not bashing them.

The code below illustrates my initial attempt at understanding
interfaces...pi eced together from a few tutorials on the web.

The classes and intefaces apper below. and the instantiation of the
objects appears at the top...and will probably shed light on my lack of
understanding of interfaces.

The first instantiation illustrates the use of the interfaces:
public partial class _Default : System.Web.UI.P age

{

protected void Page_Load(objec t sender, EventArgs e)

{

IPencil p = new Pencil();

p.Type = "Pencil";

IPencil mp = new MechanicalPenci l();

mp.Type = "MechanicalPenc il";

IPencil pen = new Pen();

pen.Type = "Pen";

PencilSharpener sharpener = new PencilSharpener ();

sharpener.Sharp en(p);

sharpener.Sharp en(mp);

sharpener.Sharp en(pen);

}

Now where I get confused is that I can quite simply get the same results
by bypassing the interfaces and never calling the PencilSharpener class:

protected void Page_Load(objec t sender, EventArgs e)

{

IPencil p = new Pencil();

p.Type = "Pencil";

p.OnSharpened() ;

IPencil mp = new MechanicalPenci l();

mp.Type = "MechanicalPenc il";

IPencil pen = new Pen();

pen.Type = "Pen";

//PencilSharpener sharpener = new PencilSharpener ();

//sharpener.Sharp en(p);

//sharpener.Sharp en(mp);

//sharpener.Sharp en(pen);

}

So this is where my paridigm needs some shifting :-)

Can you please help shed some light on this? Thank you very much!

Ron


// Interfaces +++++++++++++++ +++++++++++++++ +++

//Pencil Interface

public interface IPencil

{

string Type { get; set; }

int CurrentSharpnes s { get; set; }

bool IsSharp { get; }

void Write();

void OnSharpened();

}

//Pencil Sharpener Interface

public interface IPencilSharpene r

{

void Sharpen(IPencil pencil);

}



// Classes +++++++++++++++ +++++++++++++++ +++++++

// Pencil Class

public class Pencil : IPencil

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public Pencil()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set {

m_type = value;

m_message = "This is my " + m_type + " writing away!";

m_sharpenedMess age = "This is one sharp " + m_type + "!";

}

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = value; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

// Function

public void Write()

{

foreach (char c in m_message)

{

if (m_Sharpened == false)

{

if (IsSharp)

{

HttpContext.Cur rent.Response.W rite(c);

}

else

{

HttpContext.Cur rent.Response.W rite("#");

}

}

else

{

HttpContext.Cur rent.Response.W rite(c);

}

m_charsUsed++;

}

HttpContext.Cur rent.Response.W rite("<BR>");

}

// Function

public void OnSharpened()

{

while(this.m_cu rrentSharpness < m_message.Lengt h)

{

m_charsUsed = 0;

m_currentSharpn ess++;

Write();

}

m_Sharpened = true;

m_message = m_sharpenedMess age;

Write();

}

public void Sharpen(IPencil pencil)

{

pencil.OnSharpe ned();

}

}

// Pencil Sharpener Class

public class PencilSharpener : IPencilSharpene r

{

public void Sharpen(IPencil pencil)

{

HttpContext.Cur rent.Response.W rite("<br>Begin sharpening " + pencil.Type +
"...<br>");

pencil.OnSharpe ned();

}

}

// Pen Class

class Pen : IPencil

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public Pen()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set { m_type = value; }

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = 0; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

public void Write()

{

HttpContext.Cur rent.Response.W rite(m_message + "<BR>");

}

// Function

public void OnSharpened()

{

m_Sharpened = true;

m_message = "A Pen cannot be sharpened!.";

Write();

}

}

// Mechanical Pencil Class

class MechanicalPenci l : IPencil, IPencilSharpene r

{

private string m_message;

private string m_sharpenedMess age;

private string m_type;

private int m_currentSharpn ess;

private int m_charsUsed;

private Boolean m_Sharpened = false;

// Constructor

public MechanicalPenci l()

{

m_type = string.Empty;

m_currentSharpn ess = 0;

m_message = string.Empty;

m_sharpenedMess age = string.Empty;

m_charsUsed = 0;

}

// Property

public string Message

{

get { return m_message; }

}

// Property

public string SharpenedMessag e

{

get { return m_sharpenedMess age; }

}

// Property

public string Type

{

get { return m_type; }

set { m_type = value; }

}

// Property

public int CurrentSharpnes s

{

get { return m_currentSharpn ess; }

set { m_currentSharpn ess = value; }

}

// Property

public bool IsSharp

{

get { return m_charsUsed <= m_currentSharpn ess; }

}

// Function

public void Write()

{

foreach (char c in m_message)

{

if (m_Sharpened == false)

{

if (IsSharp)

{

HttpContext.Cur rent.Response.W rite(c);

}

else

{

HttpContext.Cur rent.Response.W rite("#");

}

}

else

{

HttpContext.Cur rent.Response.W rite(c);

}

m_charsUsed++;

}

HttpContext.Cur rent.Response.W rite("<BR>");

}

// Function

public void OnSharpened()

{

m_Sharpened = true;

m_message = "The Mechanical Pencil is self sharpening.";

Write();

}

public void Sharpen(IPencil pencil)

{

}

}

}


Oct 20 '06 #12
Sorry, I meant to write the code like this:

IMediaPlayer mp;
string playerType = "mp3"

switch(playerTy pe)
{
case "mp3" : mp = new MP3Player(); break;
case "video" : mp = new VideoPlayer(); break;
}

mp.Play();
mp.Stop();

"rmacias" wrote:
I think you get it. The example I like to use when explaining using
interfaces is the media player

public interface IMediaPlayer
{
FastForward();
Rewind()
Play();
Stop();
}

Then you can declare classes like

MP3Player : IMediaPlayer
VideoPlayer : IMediaPlayer

Each class performs the same functions, but would be implemented very
differently. You can have common code that does something like:

IMediaPlayer mp;
string playerType = "mp3"
mp = new MP3Player();
mp.Play();
mp.Stop();

mp = new VideoPlayer();
mp.Play();
mp.Stop();

Imagine interfaces being useful if you were writing a Media player that
plays audio files, video files, DVDs, etc.

Each has the same function, but are implemented differently.

"RSH" wrote:
Thanks all!

This is some really goosd stuff...and thank you Dave for that incredibly
clear explanation!!!!

Dare I post my updated code. I modified it based on my new interpretation
of interfaces.
Any comments or feedback would be greatly appreciated. I'm pretty new at
this stuff :-)

THANKS!

Ron

public partial class _Default : System.Web.UI.P age

{

protected void Page_Load(objec t sender, EventArgs e)

{

IWritingInstrum ent pencil = new Pencil();

pencil.Write();

pencil.IsWritin gPoorly = true;

pencil.IsBroken = true;

IWritingInstrum ent mpencil = new MechanicalPenci l();

mpencil.Write() ;

mpencil.IsWriti ngPoorly = true;

mpencil.IsBroke n = true;

IWritingInstrum ent pen = new Pen();

pen.Write();

pen.IsWritingPo orly = true;

pen.IsBroken = true;

}

// Interfaces +++++++++++++++ +++++++++++++++ +++

//Writing Implement Interface

public interface IRepair

{

bool IsWritingPoorly { get; set; }

void Write();

void Fix();

}

//Is Breakable Interface

public interface IReplace

{

bool IsBroken { get; set; }

void Replace();

}

//Combine Interfaces

public interface IWritingInstrum ent : IRepair, IReplace

{

}

// Classes +++++++++++++++ +++++++++++++++ +++++++

// Pencil Class

public class Pencil : IWritingInstrum ent

{

private string m_message;

private Boolean m_isWritingPoor ly;

private Boolean m_isBroken;

// Constructor

public Pencil()

{

m_isWritingPoor ly = false;

m_isBroken = false;

m_message = "";

}

// Property

public Boolean IsBroken

{

get { return m_isBroken; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Broken...we will
replace it for you...";

Write();

Replace();

m_isBroken = false;

}

}

// Property

public bool IsWritingPoorly

{

get { return m_isWritingPoor ly; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Dull...we will
sharpen it for you...";

Write();

Fix();

m_isWritingPoor ly = false;

}

}

// Function

public void Write()

{

HttpContext.Cur rent.Response.W rite(m_message + "<BR>");

}

// Function

public void Fix()

{

m_message = "The " + this.GetType(). Name + " was sharpened and is now
working great!<br>";

Write();

}

public void Replace()

{

m_message = "The " + this.GetType(). Name + " was replaced.<br>";

Write();

}

}

// Pen Class

public class Pen : IWritingInstrum ent

{

private string m_message;

private Boolean m_isWritingPoor ly;

private Boolean m_isBroken;

// Constructor

public Pen()

{

m_isWritingPoor ly = false;

m_isBroken = false;

m_message = "";

}

// Property

public Boolean IsBroken

{

get { return m_isBroken; }

set

{

m_message = "The " + this.GetType(). Name + " appears to be Broken...we will
replace it for you...";

Write();

Replace();

m_isBroken = false;

}

}

// Property

public bool IsWritingPoorly

{

get { return m_isWritingPoor ly; }

set
Oct 20 '06 #13
RSH
One last question...
I have two interfaces that I combine into a new one
public interface IRepair

{

bool IsWritingPoorly { get; set; }

void Write();

void Fix();

}

//Replace Interface

public interface IReplace

{

bool IsBroken { get; set; }

void Replace();

}

//Combine Interfaces

public interface IWritingInstrum ent : IRepair, IReplace

{

}

Now I need to add a new interface for refilling the pen. But the pencil and
Mechanical Pencil objects don't need the refill interface. So my class
declarations look like this:

public class Pencil : IWritingInstrum ent

{

.... the code goes here

}

public class MechanicalPenci l : IWritingInstrum ent

{

.... the code goes here

}

But now I need to add an interface specifically for ink WritingInstrume nts
so I add an interface:

//Refill Interface

public interface IRefill

{

bool NeedsRefilling { get; set; }

void Refill();

}

....and my class delaration looks like this:

public class Pen : IWritingInstrum ent, IRefill

{

....code goes here

}

Now for my question...

In the examples so far the objects are instantiated like this:

IWritingInstrum ent pencil = new Pencil();

IWritingInstrum ent mpencil = new MechanicalPenci l();

The problem is that I need the IWriting Instrument Interface, but in
addition I need the IRefill interface just for them pen, not the pencils.
In which case is it correct to create the object as follows?

I don't want the pencils to have a refill function, it doesn't make any
sense.

Pen pen = new Pen();

Basic testing shows that the interfaces still seem to require each member of
the "contract" so everything appears to be working correctly...so am I to
assume this is okay to do?

Thanks!

Ron

Oct 20 '06 #14
Hi Ron,

I recommend against using interfaces unless they will add some value. In your
examples, you haven't provided any requirements that lead me to believe
interfaces will be useful to you at all. For that reason it's hard to tell
you what you should and shouldn't do in your code. From the limited
requirements you've stated thus far, I'd recommend not using interfaces at
all.

If you are going to pass the pen that you defined in your example to a method
and if at some point in code you may pass a different implementation of
IWritingInstrum ent to the same method then an interface could be useful. If
not, then you probably don't need to use interfaces. Other uses for
interfaces are in COM interop and certain design patterns.

The interfaces and members you have chosen don't make much sense though. For
instance, the Write method should be on the IWritingInstrum ent interface, not
IRepair, because even instruments that can't break may need to Write something
:). And there is no reason for the IRepair and IReplace interfaces since they
must be implemented by all IWritingInstrum ent implementations anyway and you
haven't shown any external requirement for them. I think the following
solution makes more sense, considering that the interfaces you have defined
aren't based on any business requirements of which I'm unaware. My examples
afterwards use the interfaces, thus rationalizing their existence in the first
place.

interface IRefillable
{
bool ShouldRefill { get; set; }
bool CanRefill { get; }
void Refill();
}

interface IWritingInstrum ent
{
// replacement
bool ShouldReplace { get; }
bool CanReplace { get; }
void Replace();

// repair
bool IsWritingPoorly { get; set; }
bool IsBroken { get; set; }
bool CanRepair { get; }
void Repair();

// use
void Write(string words);
}

class Pen : IWritingInstrum ent, IRefillable
{
private bool broken;
public bool IsBroken { get { return broken; } set { broken = value; } }

public void Write(string words)
{
if (broken)
// don't try to write with a broken utensil!
throw new BrokenWritingIn strumentExcepti on(this); // undeclared
in my example

Console.WriteLi ne("Pen: " + words);

// crappy pen ;)
broken = true;
}
...
}

class Pencil : IWritingInstrum ent
{
public void Write(string words)
{
Console.WriteLi ne("Pencil: " + words);

// note that Pencil's don't break after writing, unlike Pens
}
...
}
....

The problem is that I need the IWriting Instrument Interface, but in
addition I need the IRefill interface just for them pen, not the pencils. In
which case is it correct to create the object as follows?
I don't want the pencils to have a refill function, it doesn't make any
sense.
Pen pen = new Pen();
I understand that you are using Pen pen = new Pen() because you want access to
your IRefill interface, but you could just as easily do the following:

IRefillable refillableUtens il = new Pen();

Now, with refillableUtens il, you can pass it to any method that accepts a
parameter of Type IRefillable. If you don't have any such methods defined (or
any use for IRefillable) then you don't need the interface. For instance, if
Pen is the only object that is IRefillable and you don't have any particular
reason to code against the IRefillable interface instead of the Pen class
itself, then just declare the Refill method in the Pen class and don't even
declare the interface.

Use the IWritingInstrum ent interface if code such as the following is desired:

void Test()
{
Pen pen = new Pen();

if (!TestWritingIn strument(pen))
Console.WriteLi ne("1: Pen is broken");
else
Console.WriteLi ne("1: Pen works just fine");

if (!TestWritingIn strument(pen))
Console.WriteLi ne("2: Pen is broken");
else
Console.WriteLi ne("2: Pen works just fine");

if (!TestWritingIn strument(new Pencil()))
Console.WriteLi ne("Pencil is broken");
else
Console.WriteLi ne("Pencil works just fine");
}

// This method doesn't know whether it's testing a Pen or a Pencil,
// which is the reason for the interface in the first place
bool TestWritingInst rument(IWriting Instrument utensil)
{
if (utensil == null)
throw new ArgumentNullExc eption("utensil ");

if (utensil.IsBrok en)
// test failed!
return false;

// if IsBroken wasn't defined we could just call Write and catch
// BrokenWritingIn strumentExcepti on and then return false

utensil.Write(" This is a test!");

// assume test passed
return true;
}
For the sake of using IRefillable in an example, you could have a method such
as the following:

void Write(IWritingI nstrument utensil, string words)
{
if (utensil == null)
throw new ArgumentNullExc eption("utensil ");

if (utensil.Should Replace)
utensil.Replace ();

IRefillable refillable = utensil as IRefillable;

if (refillable != null && refillable.Shou ldRefill)
{
if (refillable.Can Refill)
refillable.Refi ll();
else if (utensil.CanRep lace)
utensil.Replace ();
else
throw new InvalidOperatio nException("The writing instrument is
empty and cannot be refilled or replaced at this time.");
}

// this method may throw BrokenWritingIn strumentExcepti on,
// which is not defined in my example
utensil.Write(w ords);
}
With the above method defined you can write with any IWritingInstrum ent and be
sure not to run out of "juice":

Write(new Pen(), "Test custom Write method");
Write(new Pencil(), "Test custom Write method");
(Please note that I haven't tested this code so it will probably require
modifications to build correctly)

--
Dave Sexton

"RSH" <wa************ *@yahoo.comwrot e in message
news:uf******** *****@TK2MSFTNG P05.phx.gbl...
One last question...
I have two interfaces that I combine into a new one
public interface IRepair

{

bool IsWritingPoorly { get; set; }

void Write();

void Fix();

}

//Replace Interface

public interface IReplace

{

bool IsBroken { get; set; }

void Replace();

}

//Combine Interfaces

public interface IWritingInstrum ent : IRepair, IReplace

{

}

Now I need to add a new interface for refilling the pen. But the pencil and
Mechanical Pencil objects don't need the refill interface. So my class
declarations look like this:

public class Pencil : IWritingInstrum ent

{

... the code goes here

}

public class MechanicalPenci l : IWritingInstrum ent

{

... the code goes here

}

But now I need to add an interface specifically for ink WritingInstrume nts
so I add an interface:

//Refill Interface

public interface IRefill

{

bool NeedsRefilling { get; set; }

void Refill();

}

...and my class delaration looks like this:

public class Pen : IWritingInstrum ent, IRefill

{

...code goes here

}

Now for my question...

In the examples so far the objects are instantiated like this:

IWritingInstrum ent pencil = new Pencil();

IWritingInstrum ent mpencil = new MechanicalPenci l();

The problem is that I need the IWriting Instrument Interface, but in
addition I need the IRefill interface just for them pen, not the pencils. In
which case is it correct to create the object as follows?

I don't want the pencils to have a refill function, it doesn't make any
sense.

Pen pen = new Pen();

Basic testing shows that the interfaces still seem to require each member of
the "contract" so everything appears to be working correctly...so am I to
assume this is okay to do?

Thanks!

Ron



Oct 20 '06 #15
RSH
Oh Dave I have way too much to learn...thank you for your assistance. Just
when i thought I was beginning to understand interfaces :-)

Thank you for your time!
Ron

"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:u1******** ******@TK2MSFTN GP04.phx.gbl...
Hi Ron,

I recommend against using interfaces unless they will add some value. In
your examples, you haven't provided any requirements that lead me to
believe interfaces will be useful to you at all. For that reason it's
hard to tell you what you should and shouldn't do in your code. From the
limited requirements you've stated thus far, I'd recommend not using
interfaces at all.

If you are going to pass the pen that you defined in your example to a
method and if at some point in code you may pass a different
implementation of IWritingInstrum ent to the same method then an interface
could be useful. If not, then you probably don't need to use interfaces.
Other uses for interfaces are in COM interop and certain design patterns.

The interfaces and members you have chosen don't make much sense though.
For instance, the Write method should be on the IWritingInstrum ent
interface, not IRepair, because even instruments that can't break may need
to Write something :). And there is no reason for the IRepair and
IReplace interfaces since they must be implemented by all
IWritingInstrum ent implementations anyway and you haven't shown any
external requirement for them. I think the following solution makes more
sense, considering that the interfaces you have defined aren't based on
any business requirements of which I'm unaware. My examples afterwards
use the interfaces, thus rationalizing their existence in the first place.

interface IRefillable
{
bool ShouldRefill { get; set; }
bool CanRefill { get; }
void Refill();
}

interface IWritingInstrum ent
{
// replacement
bool ShouldReplace { get; }
bool CanReplace { get; }
void Replace();

// repair
bool IsWritingPoorly { get; set; }
bool IsBroken { get; set; }
bool CanRepair { get; }
void Repair();

// use
void Write(string words);
}

class Pen : IWritingInstrum ent, IRefillable
{
private bool broken;
public bool IsBroken { get { return broken; } set { broken = value; } }

public void Write(string words)
{
if (broken)
// don't try to write with a broken utensil!
throw new BrokenWritingIn strumentExcepti on(this); //
undeclared in my example

Console.WriteLi ne("Pen: " + words);

// crappy pen ;)
broken = true;
}
...
}

class Pencil : IWritingInstrum ent
{
public void Write(string words)
{
Console.WriteLi ne("Pencil: " + words);

// note that Pencil's don't break after writing, unlike Pens
}
...
}
...

>The problem is that I need the IWriting Instrument Interface, but in
addition I need the IRefill interface just for them pen, not the pencils.
In which case is it correct to create the object as follows?
I don't want the pencils to have a refill function, it doesn't make any
sense.
Pen pen = new Pen();

I understand that you are using Pen pen = new Pen() because you want
access to your IRefill interface, but you could just as easily do the
following:

IRefillable refillableUtens il = new Pen();

Now, with refillableUtens il, you can pass it to any method that accepts a
parameter of Type IRefillable. If you don't have any such methods defined
(or any use for IRefillable) then you don't need the interface. For
instance, if Pen is the only object that is IRefillable and you don't have
any particular reason to code against the IRefillable interface instead of
the Pen class itself, then just declare the Refill method in the Pen class
and don't even declare the interface.

Use the IWritingInstrum ent interface if code such as the following is
desired:

void Test()
{
Pen pen = new Pen();

if (!TestWritingIn strument(pen))
Console.WriteLi ne("1: Pen is broken");
else
Console.WriteLi ne("1: Pen works just fine");

if (!TestWritingIn strument(pen))
Console.WriteLi ne("2: Pen is broken");
else
Console.WriteLi ne("2: Pen works just fine");

if (!TestWritingIn strument(new Pencil()))
Console.WriteLi ne("Pencil is broken");
else
Console.WriteLi ne("Pencil works just fine");
}

// This method doesn't know whether it's testing a Pen or a Pencil,
// which is the reason for the interface in the first place
bool TestWritingInst rument(IWriting Instrument utensil)
{
if (utensil == null)
throw new ArgumentNullExc eption("utensil ");

if (utensil.IsBrok en)
// test failed!
return false;

// if IsBroken wasn't defined we could just call Write and catch
// BrokenWritingIn strumentExcepti on and then return false

utensil.Write(" This is a test!");

// assume test passed
return true;
}
For the sake of using IRefillable in an example, you could have a method
such as the following:

void Write(IWritingI nstrument utensil, string words)
{
if (utensil == null)
throw new ArgumentNullExc eption("utensil ");

if (utensil.Should Replace)
utensil.Replace ();

IRefillable refillable = utensil as IRefillable;

if (refillable != null && refillable.Shou ldRefill)
{
if (refillable.Can Refill)
refillable.Refi ll();
else if (utensil.CanRep lace)
utensil.Replace ();
else
throw new InvalidOperatio nException("The writing instrument is
empty and cannot be refilled or replaced at this time.");
}

// this method may throw BrokenWritingIn strumentExcepti on,
// which is not defined in my example
utensil.Write(w ords);
}
With the above method defined you can write with any IWritingInstrum ent
and be sure not to run out of "juice":

Write(new Pen(), "Test custom Write method");
Write(new Pencil(), "Test custom Write method");
(Please note that I haven't tested this code so it will probably require
modifications to build correctly)

--
Dave Sexton

"RSH" <wa************ *@yahoo.comwrot e in message
news:uf******** *****@TK2MSFTNG P05.phx.gbl...
>One last question...
I have two interfaces that I combine into a new one
public interface IRepair

{

bool IsWritingPoorly { get; set; }

void Write();

void Fix();

}

//Replace Interface

public interface IReplace

{

bool IsBroken { get; set; }

void Replace();

}

//Combine Interfaces

public interface IWritingInstrum ent : IRepair, IReplace

{

}

Now I need to add a new interface for refilling the pen. But the pencil
and Mechanical Pencil objects don't need the refill interface. So my
class declarations look like this:

public class Pencil : IWritingInstrum ent

{

... the code goes here

}

public class MechanicalPenci l : IWritingInstrum ent

{

... the code goes here

}

But now I need to add an interface specifically for ink
WritingInstrum ents so I add an interface:

//Refill Interface

public interface IRefill

{

bool NeedsRefilling { get; set; }

void Refill();

}

...and my class delaration looks like this:

public class Pen : IWritingInstrum ent, IRefill

{

...code goes here

}

Now for my question...

In the examples so far the objects are instantiated like this:

IWritingInstru ment pencil = new Pencil();

IWritingInstru ment mpencil = new MechanicalPenci l();

The problem is that I need the IWriting Instrument Interface, but in
addition I need the IRefill interface just for them pen, not the pencils.
In which case is it correct to create the object as follows?

I don't want the pencils to have a refill function, it doesn't make any
sense.

Pen pen = new Pen();

Basic testing shows that the interfaces still seem to require each member
of the "contract" so everything appears to be working correctly...so am I
to assume this is okay to do?

Thanks!

Ron




Oct 23 '06 #16
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:u1******** ******@TK2MSFTN GP04.phx.gbl...
>
I recommend against using interfaces unless they will add some value. In
your examples, you haven't provided any requirements that lead me to
believe interfaces will be useful to you at all. For that reason it's
hard to tell you what you should and shouldn't do in your code. From the
limited requirements you've stated thus far, I'd recommend not using
interfaces at all.
In another thread, you were looking for some agreement between us. Consider
it found. :)

///ark
Oct 23 '06 #17
Hi Mark,

I'm glad to hear that you agree with me on the point I made about the OP's use
of interfaces :)

But in our conversation I wasn't looking for agreement just for the sake of
agreeing, but instead for the sake of learning. When a conversation ends
without agreement, everyone's left with one or more competing ideas and no
solution, although I think we located the root of our difference of opinion
anyway.

--
Dave Sexton

"Mark Wilden" <mw*****@commun itymtm.comwrote in message
news:O5******** ******@TK2MSFTN GP03.phx.gbl...
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:u1******** ******@TK2MSFTN GP04.phx.gbl...
>>
I recommend against using interfaces unless they will add some value. In
your examples, you haven't provided any requirements that lead me to
believe interfaces will be useful to you at all. For that reason it's hard
to tell you what you should and shouldn't do in your code. From the
limited requirements you've stated thus far, I'd recommend not using
interfaces at all.

In another thread, you were looking for some agreement between us. Consider
it found. :)

///ark


Oct 23 '06 #18
Hi,

Dave Sexton wrote:
Hi Mark,

I'm glad to hear that you agree with me on the point I made about the OP's use
of interfaces :)

But in our conversation I wasn't looking for agreement just for the sake of
agreeing, but instead for the sake of learning. When a conversation ends
without agreement, everyone's left with one or more competing ideas and no
solution, although I think we located the root of our difference of opinion
anyway.
I think there can be learning without agreement (unless I misunderstand
what agreement really means in english). I still don't really agree with
Mark's thoughts about documenting the source code, but I have thought *a
lot* about it since we talked about that, and I think it will help me to
be more efficient about my coding.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Oct 23 '06 #19
Hi Laurent,

I didn't mean to imply that our conversation was pointless. I believe it was
helpful to me as well. I was trying to come to an agreement with Mark for the
sake of learning so we could validate or disproove our beliefs and have a
better understanding of what is the "right way of doing things". We never
came to such an agreement because we disagreed on other things that were
off-topic, as I pointed out.

I only replied with that statement because it seemed that Mark's comments were
meant to say, "here's your agreement, Dave". That's not what I wanted when I
asked to agree on something - just any agreement on anything, even something
completely unrelated such as the use of interfaces :)

--
Dave Sexton

"Laurent Bugnion" <ga*********@bl uewin.chwrote in message
news:uc******** ******@TK2MSFTN GP05.phx.gbl...
Hi,

Dave Sexton wrote:
>Hi Mark,

I'm glad to hear that you agree with me on the point I made about the OP's
use of interfaces :)

But in our conversation I wasn't looking for agreement just for the sake of
agreeing, but instead for the sake of learning. When a conversation ends
without agreement, everyone's left with one or more competing ideas and no
solution, although I think we located the root of our difference of opinion
anyway.

I think there can be learning without agreement (unless I misunderstand what
agreement really means in english). I still don't really agree with Mark's
thoughts about documenting the source code, but I have thought *a lot* about
it since we talked about that, and I think it will help me to be more
efficient about my coding.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch

Oct 23 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
1522
by: Tom | last post by:
Hello, I've recently started trying to learn C (for the fun of it!). I have been using Perl and other languages for many years, but they were always very high level, this is giving me quite a ride. Here is my situation: I have the following code: ////////////////////////////////////////////////////////////
6
1927
by: dotNeter | last post by:
The services, talked here, are things used in IServiceContainer, IServiceProvider, etc. In my opinion, everything can be a service, and a service is generally used for providing specific features for service consumers, at design time. But, I think the cnsumers must completely know all aspects of that service. This sounds not good, and breaks the decoupling rule. So how to understand the role of Service, in a software engineering...
27
3852
by: jm | last post by:
I am having trouble understanding the purposes of an interface, even though the concept of interfaces is around me all the time (user interface, for example). I'm just not understanding software interfaces. Like anything else, it appears Interfaces are by design something that requires documentation. I know this may be obvious, but if I have a class A and I say, well, class A implements IMyInterface. The fact that it implements...
0
9452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9237
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9184
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8187
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6033
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4551
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3262
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.