473,883 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Collecti ons.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.WriteLi ne( "Creating document with: {0}", s );
}
// implement the Read method
public void Read()
{
Console.WriteLi ne(
"Implementi ng the Read Method for IStorable" );
}

// implement the Write method
public void Write( object o )
{
Console.WriteLi ne(
"Implementi ng 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.WriteLi ne( "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 6086
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
IReadOnlySessio nState, INamingContaine r and IRequiresSessio nState.

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(ISt oreable 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*******@hotm ail.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
"inheritanc e", 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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Nick Malik [Microsoft] <ni*******@hotm ail.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
"inheritanc e", 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.co m>
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*******@hotm ail.nospam.com> wrote in message
news:6I******** ************@co mcast.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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Nick Malik [Microsoft] <ni*******@hotm ail.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
"inheritanc e", 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.co m>
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
4312
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 must be many know the answer here. thanks
12
3313
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. Such things happen. The whole subsystem is going through radical changes. I don't really want to say what I think of the code just yet. That would influence the opinions of others, and I really want to know how other people view these things,...
72
5923
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 example, between a C/C++ programmers with a few weeks of experience and a C/C++ programmer with years of experience. You don't really need to understand the subtle details or use the obscure features of either language
140
7941
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
23910
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 believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is basically the same. in C there arent the simplest things present like constants, each struct and enum...
23
1916
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 could be a tedious process though) but I haven't been able to pick up the practical advantages of XAML. From my assessment, XAML will provide separation of UI logic from business rules/procedures for applications. It seems like an HTML of sorts for...
26
4523
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 System.EnterpriseServices;
9
4269
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 create a Dispose method to clean up resources I have to either call it explicitly or call it in the destructor to make it run. I've tried it both with and without implementing IDisposable and it doesn't seem to make a difference to the GC. Either...
669
26391
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 paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
0
9942
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9792
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10743
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
10847
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
10416
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
9574
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 projectplanning, coding, testing, and deploymentwithout 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...
1
7971
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5797
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...
2
4220
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.