Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

what's the point of an interface?

0 views
Skip to first unread message

John Salerno

unread,
May 26, 2005, 10:37:35 PM5/26/05
to
I understand how they work (basically), but I think maybe the examples
I'm reading are too elementary to really show their value. Here's one
from Programming C#:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace SimpleInterface
{
// declare the interface

interface IStorable
{
// no access modifiers, methods are public
// no implementation
void Read();
void Write( object obj );
int Status { get; set; }

}


// create a class which implements the IStorable interface
public class Document : IStorable
{

// store the value for the property
private int status = 0;

public Document( string s )
{
Console.WriteLine( "Creating document with: {0}", s );
}


// implement the Read method
public void Read()
{
Console.WriteLine(
"Implementing the Read Method for IStorable" );
}

// implement the Write method
public void Write( object o )
{
Console.WriteLine(
"Implementing the Write Method for IStorable" );
}

// implement the property
public int Status
{
get
{
return status;
}

set
{
status = value;
}
}
}

// Take our interface out for a spin
public class Tester
{

static void Main()
{
// access the methods in the Document object
Document doc = new Document( "Test Document" );
doc.Status = -1;
doc.Read();
Console.WriteLine( "Document Status: {0}", doc.Status );
}
}
}


My question is, what is gained by even using the interface? If you have
to implement the methods and property in the class anyway, couldn't you
just leave the class as it is, without the interface, and it would still
work?

Jeff Louie

unread,
May 27, 2005, 12:00:20 AM5/27/05
to
Look at an interface as a contract between the caller and supplier. When
I am writing a class I first write the interfaces. I then implement the
interfaces in a class. Often, I write a basic incomplete implementation
of the interface as an abstract class and then inherit from this
abstract class in a concrete class.

This is an example of interface based programming. So if you are
providing a software service over the wire, you write and publish the
interface. Users of your service see what your service provides via the
interface contract. They do not care or need to know the awful details
of how you provide the service. This is the power of encapsulation or
information hiding.

The second use of an interface is when you have some complex logic that
you want to reuse. There may be one method call that will differ between
users of the algorithm. You can declare that user specific method in an
interface. Your complex algorithm can then provide a method call in
which the user passes in an object that implements this interface. In
your method you call this interface method. This allows many clients to
reuse the complex logic of your algorithm by simple providing the custom
implementation of the final interface method. This is the power of
deferring the final implementation details to a more knowledgeable
client.

The third use of an interface is when you want to use the power of
polymorphism. In this technique, multiple classes all provide an
implementation of a single interface. You can then store instances of
these many different classes and simply call the interface method. There
is no need to cast each instance to the specific concrete class. A
printing framework composed of multiple widgets that all know how to
print themselves is an example of using polymorphism. This is the power
of polymorphism through inheritance. This is different from compile time
polymorphism or generic programming or so called "duck typing." (So at
compile time if it looks like a duck, walks like a duck and quacks like
a duck, it _is_ a duck.)

The third sometimes frowned upon use of interfaces is as a marker. The
interface can be empty. If the class implements the empty interface it
is marked. As an example, the .NET API uses the marker interfaces
IReadOnlySessionState, INamingContainer and IRequiresSessionState.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***

Bruce Wood

unread,
May 27, 2005, 12:40:37 AM5/27/05
to
First, let me answer your direct question,

> My question is, what is gained by even using the interface? If you have
> to implement the methods and property in the class anyway, couldn't you
> just leave the class as it is, without the interface, and it would still
> work?

Well, yes. The question is, "work for what purpose"? Would the property
and the method still do what they were designed to do? Yes. However,
the value of an interface appears when you implement it in more than
one class.

Think of the IStoreable example you gave. What if you want dozens of
classes, which have no particular relationship with each other in the
traditional, "is-a" class hierarchy sense, but which you want to make
"IStoreable"? If you implement the interface in all those dozens of
classes, they will all have identical Read(), Write(), and Status
members.

Well, so what? Without the interface you could still write Read(),
Write(), and Status in each class and have them all work. The payoff
comes when you want to write other methods that accept as parameters
"anything that is IStoreable":

public void WriteToHtml(IStoreable itemToWrite)
{
...
}

public IStoreable ReadFromHtml()
{
...
}

What these methods say is, I will accept any object of any type that
implements the IStoreable interface." This is an example of
_polymorphism_: the methods will accept / return _any type_ (poly -
morph) of object, so long as it implements IStoreable.

This is a simplistic use of interfaces, but it gives you a basic idea
to start with.

In more sophisticated design patterns, interfaces are used to define
_contracts_ between layers of your architecture. For example, you could
write a layer of business classes that understand how to manipulate the
objects pertinent to your business. These objects need to have some way
of storing business objects to the database and retrieving them from
the database, but they don't want to have to know the details, nor even
which database they're talking to.

So, your business layer defines an interface that contains the methods
and properties that it will require of any data layer that it talks to.
The interface would declare methods such as StoreCustomer,
FetchCustomer, DeleteCustomer, etc. What the business layer is saying
is, "I will work with any data layer that implements these methods that
I need. Apart from that, I care nothing about how this data is stored."
So, interfaces can give you plug-and-play database layers. (For
example, my application has a real database layer that talks through
ODBC, and I have a "fake" test layer for running unit tests, that
doesn't really talk to any database. The business layer neither knows
nor cares which one it's talking to, so long as they both provide the
correct functionality as defined by the interface.)

Anyway, there are some ideas. Have fun learning O-O!

Nick Malik [Microsoft]

unread,
May 27, 2005, 2:09:29 AM5/27/05
to
minor nit

> The third use of an interface is when you want to use the power of
> polymorphism. In this technique, multiple classes all provide an
> implementation of a single interface. You can then store instances of
> these many different classes and simply call the interface method.

This is inheritance, not polymorphism.

The rest of your post is well reasoned and tuned well to the level of the
OP.

To the OP: You are ready to begin reading about design patterns.
See:
http://blogs.msdn.com/nickmalik/archive/2004/12/21/328727.aspx

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--


Jon Skeet [C# MVP]

unread,
May 27, 2005, 2:21:07 AM5/27/05
to
Nick Malik [Microsoft] <nick...@hotmail.nospam.com> wrote:
> minor nit
>
> > The third use of an interface is when you want to use the power of
> > polymorphism. In this technique, multiple classes all provide an
> > implementation of a single interface. You can then store instances of
> > these many different classes and simply call the interface method.
>
> This is inheritance, not polymorphism.

I disagree - it's inheritance of interface rather than inheritance of
implementation which is often understood by just the term
"inheritance", and it fits in well with all the definitions of
polymorphism I've seen. For instance:

<quote>
In computer science, polymorphism is the idea of allowing the same code
to be used with different classes of data (which classes in typed
languages correspond to types), resulting in more general and abstract
implementations.
</quote>

and

<quote>
In object-oriented programming theory, polymorphism is the ability of
objects belonging to different types to respond to methods of the same
name, each one according to the right type-specific behavior. The
programmer (and the program) does not have to know the exact type of
the object in advance, so this behavior can be implemented at run time
(this is called late binding or dynamic binding).
</quote>

That sounds like what Jeff was describing to me - admittedly without
the detail of "You can then store instances of these many different
classes [knowing only that they implement the interface] and simply
call the interface method."

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nick Malik [Microsoft]

unread,
May 27, 2005, 9:35:07 AM5/27/05
to
After I posted my note, I did the same thing you did... I looked up common
definitions for polymorphism. You are correct: inheritance of an interface
is considered to be a form of polymorphism. One of the better articles for
describing this term is:
http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29

In this context, inheritance acts as "Subtyping polymorphism".

I was in the mindset of "Ad-hoc polymorphism" when I typed my comment.

I withdraw my comment.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--

"Jon Skeet [C# MVP]" <sk...@pobox.com> wrote in message
news:MPG.1d00cca62...@msnews.microsoft.com...

Alvin Bruney [MVP - ASP.NET]

unread,
May 28, 2005, 11:55:59 PM5/28/05
to
...and that's one reason why programming is overly complexed because most
times we can't even agree on what it really is. aside from all the chatter
(correct chatter anyway) i find interfaces very useful for decoupling two
objects - that is if you want to decouple, position an interface between
the two objects.

--
Regards,
Alvin Bruney - ASP.NET MVP

[Shameless Author Plug]
The Microsoft Office Web Components Black Book with .NET
Now available @ www.lulu.com/owc, Amazon.com etc
"Nick Malik [Microsoft]" <nick...@hotmail.nospam.com> wrote in message
news:6I2dnaPgoO9...@comcast.com...

0 new messages