Interfaces

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Phil D

    #1

    Interfaces

    Hi,

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

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

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

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

    Many Thanks

    Phil D


  • Eddy

    #2
    Re: Interfaces

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

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

    Eddy

    "Phil D" <no.spam@invali d.btinternet.co m> wrote in message
    news:OF5a$XQrDH A.708@TK2MSFTNG P10.phx.gbl...[color=blue]
    > Hi,
    >
    > I am new to c# and oop and have a question about interfaces which I hope
    > someone can help me with.
    >
    > The book I am using (C# Step by Step) explains how to create and implement
    > interfaces (in terms of syntax and grammar), but what it doesn't cover is
    > why I'd use an interface, and the reasons for doing so.
    >
    > Currently I just can't see what the value of an interface is, or why I'd
    > ever want to use one.
    >
    > Could someone either explain this to me simply, or point me to some good
    > references (web or books) which cover this topic.
    >
    > Many Thanks
    >
    > Phil D
    >
    >[/color]


    Comment

    • irfan

      #3
      Re: Interfaces

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

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

      Comment

      • Jerry Negrelli

        #4
        Interfaces

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

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

        JER
        [color=blue]
        >-----Original Message-----
        >Hi,
        >
        >I am new to c# and oop and have a question about[/color]
        interfaces which I hope[color=blue]
        >someone can help me with.
        >
        >The book I am using (C# Step by Step) explains how to[/color]
        create and implement[color=blue]
        >interfaces (in terms of syntax and grammar), but what it[/color]
        doesn't cover is[color=blue]
        >why I'd use an interface, and the reasons for doing so.
        >
        >Currently I just can't see what the value of an[/color]
        interface is, or why I'd[color=blue]
        >ever want to use one.
        >
        >Could someone either explain this to me simply, or point[/color]
        me to some good[color=blue]
        >references (web or books) which cover this topic.
        >
        >Many Thanks
        >
        >Phil D
        >
        >
        >.
        >[/color]

        Comment

        • Tobes \(Breath\)

          #5
          Re: Interfaces

          "Phil D" <no.spam@invali d.btinternet.co m> wrote in message
          news:OF5a$XQrDH A.708@TK2MSFTNG P10.phx.gbl...[color=blue]
          > Currently I just can't see what the value of an interface is, or why I'd
          > ever want to use one.[/color]

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

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

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

          Better Software - By Lecture, demonstration, and by example. Experts helping you succeed through training, mentoring, coaching, and development.


          Some relevant ones might be:

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

          HTH

          Tobes
          [color=blue]
          > Many Thanks
          >
          > Phil D
          >
          >[/color]


          Comment

          • Kenneth Baltrinic

            #6
            Re: Interfaces (A simple example/answer)

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

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

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

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

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

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

            /// <summary>
            /// Opens a file of one of the types specified by GetSupportedFil eTypes.
            /// </summary>
            /// <param name="FileName" ></param>
            /// <returns>Return s true if the document was opened, false
            otherwise.</returns>
            bool OpenFromFile(st ring FileName);

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

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

            }


            "Phil D" <no.spam@invali d.btinternet.co m> wrote in message
            news:OF5a$XQrDH A.708@TK2MSFTNG P10.phx.gbl...[color=blue]
            > Hi,
            >
            > I am new to c# and oop and have a question about interfaces which I hope
            > someone can help me with.
            >
            > The book I am using (C# Step by Step) explains how to create and implement
            > interfaces (in terms of syntax and grammar), but what it doesn't cover is
            > why I'd use an interface, and the reasons for doing so.
            >
            > Currently I just can't see what the value of an interface is, or why I'd
            > ever want to use one.
            >
            > Could someone either explain this to me simply, or point me to some good
            > references (web or books) which cover this topic.
            >
            > Many Thanks
            >
            > Phil D
            >
            >[/color]


            Comment

            • Phil D

              #7
              Re: Interfaces

              Thanks for your replies guys.

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

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

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

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

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

              Phil D

              ps Apologies if i seem really dense !!

              "Eddy" <sourcecode@pan dora.be> wrote in message
              news:eAiC4rQrDH A.2892@TK2MSFTN GP10.phx.gbl...[color=blue]
              > An interface is used when there is no default implementation to inherit.
              > Whereas an abstract class is best used for prividing data and services for
              > objects in a hierarchical relationship, an interface can be used for
              > prividing services that "bring together" disparate objects that relate to
              > one another only through that interface.
              > A class that implement an interface sings a contract with the compiler[/color]
              that[color=blue]
              > says "this class will define all the properties and methods specified by[/color]
              the[color=blue]
              > interface."
              > Interfaces provide uniform sets of methods and properties for objects of
              > disparate classes. These methods and properties enable programs to process
              > the objects of those disparate classes polymorphically .
              >
              > For example a person and a tree, these objects have nothing in comon, it's
              > illogical to inherit from a base object. But, both objects have an age.[/color]
              You[color=blue]
              > can implement this property through an interface and then handle these
              > objects polymorphically .
              >
              > Eddy
              >
              > "Phil D" <no.spam@invali d.btinternet.co m> wrote in message
              > news:OF5a$XQrDH A.708@TK2MSFTNG P10.phx.gbl...[color=green]
              > > Hi,
              > >
              > > I am new to c# and oop and have a question about interfaces which I hope
              > > someone can help me with.
              > >
              > > The book I am using (C# Step by Step) explains how to create and[/color][/color]
              implement[color=blue][color=green]
              > > interfaces (in terms of syntax and grammar), but what it doesn't cover[/color][/color]
              is[color=blue][color=green]
              > > why I'd use an interface, and the reasons for doing so.
              > >
              > > Currently I just can't see what the value of an interface is, or why I'd
              > > ever want to use one.
              > >
              > > Could someone either explain this to me simply, or point me to some good
              > > references (web or books) which cover this topic.
              > >
              > > Many Thanks
              > >
              > > Phil D
              > >
              > >[/color]
              >
              >[/color]


              Comment

              • Frank Oquendo

                #8
                Re: Interfaces

                Phil D wrote:
                [color=blue]
                > However, I could just access those properties directly via myTree.Age
                > or myPerson.Height so I'm not sure what I've gained by using the
                > interface.[/color]

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

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

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

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

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


                (Pull the pin to reply)


                Comment

                • Phil D

                  #9
                  Re: Interfaces (A simple example/answer)

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

                  Phil D

                  "Kenneth Baltrinic" <kenneth@baltri nic.com> wrote in message
                  news:uzjMntTrDH A.2588@tk2msftn gp13.phx.gbl...[color=blue]
                  > Here is an example that may help you understand the purpose of interfaces.
                  >
                  > I often use interfaces to define a "plug-in" archetecture. If I have a
                  > parent application that I want others to be able to write a module for, I
                  > define an interface, (and provide the neccesary documenation for it).[/color]
                  Then[color=blue]
                  > others can develope a module (typically a dll) that provides a publicly
                  > instatiatable class that defines my interface.
                  >
                  > I have to provide some mechanism whereby they can "register" their module
                  > with my app so that the app has the information it needs to dynamically[/color]
                  load[color=blue]
                  > an instance that public class. Once I load this class and place it in a
                  > variable declared to by of my Interface type, I can used it with[/color]
                  confidence[color=blue]
                  > because I know it supports all the members I need in order for it to
                  > interact with my app. Below is a simple inteface that I have used in the
                  > past.
                  >
                  > /// <summary>
                  > /// This interface is implemented by any class that acts as the public
                  > interface of a
                  > /// Configuration Application Module. It defines the methods and
                  > properties through which
                  > /// the configuration application will comunicate with the module.
                  > /// </summary>
                  > public interface IConfigAppModul e
                  > {
                  > /// <summary>
                  > /// This method must be called after instantiating any new object module
                  > prior to invoking
                  > /// any other members of the object except ModuleName,
                  > GetSupportedFil eTypes and
                  > /// GetSupportedNew DocumentTypes.
                  > /// </summary>
                  > /// <param name="Host"></param>
                  > /// <returns>Return s true if the module successfully initializes, false
                  > otherwise. A moduel
                  > /// that returns false should be discarded and not used. A module that
                  > returns false is
                  > /// responsible for notifing the user of any errors encountered.</return[/color]
                  s>[color=blue]
                  > bool InitModule(IHos tConfigApp Host);
                  >
                  > /// <summary>
                  > /// Returns a short human readable name of this module.
                  > /// </summary>
                  > string Name { get; }
                  >
                  > /// <summary>
                  > /// Provide the host application with a list of file types that this
                  > module is capable of
                  > /// opening with the Open() method.
                  > /// </summary>
                  > /// <returns>Return s a two dementional array of size [n,1] where n is[/color]
                  the[color=blue]
                  > number of file
                  > /// types supported. For each file type x [x,0] is the human[/color]
                  description[color=blue]
                  > of the file type
                  > /// and [x,1] is the file extention used by the file type. E.g. [0,0] =
                  > "Text Files"
                  > /// [0,1] = ".txt" </returns>
                  > string[,] GetSupportedFil eTypes();
                  >
                  > /// <summary>
                  > /// Opens a file of one of the types specified by GetSupportedFil eTypes.
                  > /// </summary>
                  > /// <param name="FileName" ></param>
                  > /// <returns>Return s true if the document was opened, false
                  > otherwise.</returns>
                  > bool OpenFromFile(st ring FileName);
                  >
                  > /// <summary>
                  > /// Provide the host application with a list of Document types that this
                  > module is capable of
                  > /// opening with the OpenNewDocument () method.
                  > /// </summary>
                  > /// <returns>Return s an array of strings where each string is the[/color]
                  display[color=blue]
                  > text of the menu entry
                  > /// (or other control) that the user will select to request a new[/color]
                  document[color=blue]
                  > of a supported type.
                  > /// This same string is also passed to OpenNewDocument to indicate the
                  > type of document to open.</returns>
                  > string[] GetSupportedNew DocumentTypes() ;
                  >
                  > /// <summary>
                  > /// Opens a new document of the type specified.
                  > /// </summary>
                  > /// <param name="TypeName" >The name of the document type to open as
                  > orriginally provided by
                  > /// GetSupportedNew DocumentTypes() .</param>
                  > /// <returns>Return s true a document was opened, false
                  > otherwise.</returns>
                  > bool OpenNewDocument (string TypeName);
                  >
                  > }
                  >
                  >
                  > "Phil D" <no.spam@invali d.btinternet.co m> wrote in message
                  > news:OF5a$XQrDH A.708@TK2MSFTNG P10.phx.gbl...[color=green]
                  > > Hi,
                  > >
                  > > I am new to c# and oop and have a question about interfaces which I hope
                  > > someone can help me with.
                  > >
                  > > The book I am using (C# Step by Step) explains how to create and[/color][/color]
                  implement[color=blue][color=green]
                  > > interfaces (in terms of syntax and grammar), but what it doesn't cover[/color][/color]
                  is[color=blue][color=green]
                  > > why I'd use an interface, and the reasons for doing so.
                  > >
                  > > Currently I just can't see what the value of an interface is, or why I'd
                  > > ever want to use one.
                  > >
                  > > Could someone either explain this to me simply, or point me to some good
                  > > references (web or books) which cover this topic.
                  > >
                  > > Many Thanks
                  > >
                  > > Phil D
                  > >
                  > >[/color]
                  >
                  >[/color]


                  Comment

                  Working...