473,387 Members | 1,530 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

what's the point of an interface?

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?
Nov 17 '05 #1
6 6054
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 ***
Nov 17 '05 #2
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!

Nov 17 '05 #3
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/arch...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.
--
Nov 17 '05 #4
Nick Malik [Microsoft] <ni*******@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
Nov 17 '05 #5
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/Polymor...ter_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:MP************************@msnews.microsoft.c om...
Nick Malik [Microsoft] <ni*******@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

Nov 17 '05 #6
....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]" <ni*******@hotmail.nospam.com> wrote in message
news:6I********************@comcast.com...
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/Polymor...ter_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:MP************************@msnews.microsoft.c om...
Nick Malik [Microsoft] <ni*******@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


Nov 17 '05 #7

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

Similar topics

44
by: lester | last post by:
a pre-beginner's question: what is the pros and cons of .net, compared to ++ I am wondering what can I get if I continue to learn C# after I have learned C --> C++ --> C# ?? I think there...
12
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. ...
72
by: E. Robert Tisdale | last post by:
What makes a good C/C++ programmer? Would you be surprised if I told you that it has almost nothing to do with your knowledge of C or C++? There isn't much difference in productivity, for...
140
by: Oliver Brausch | last post by:
Hello, have you ever heard about this MS-visual c compiler bug? look at the small prog: static int x=0; int bit32() { return ++x; }
687
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't...
23
by: JDeats | last post by:
Just spent some time browsing around here: http://msdn.microsoft.com/Longhorn/ I can see the benefits from WinFS (as long as we tag all in-coming data this should be nice, tagging everything...
26
by: Lasse Edsvik | last post by:
Hello I'm trying to build a simple COM+ app in vs.net using C# and i cant register it in component manager..... what more is needed than this: using System; using...
9
by: CMirandaman | last post by:
Perhaps someone can help me understand this. I'm trying to understand what the IDisposable interface actually does because as far as I can tell it seems to be just garnish on the plate. If I...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.