Strugglnig understanding the reason behind interfaces

Last post 03-31-2008 8:01 AM by Suprotim Agarwal. 8 replies.

Sort Posts:

  • Strugglnig understanding the reason behind interfaces

    03-29-2008, 2:59 AM
    • Member
      125 point Member
    • JohnCogan2
    • Member since 03-07-2006, 10:44 AM
    • Posts 35

    Hi all

    Sorry for asking what may seem like a very basic question, but I am struggling a little with understanding how interfaces work when it comes to inheritance.

    I understand how an interface is created and how its methods need to be included in the implementing class.

    What I am having trouble understanding is why we do this. If you have to implmenet all the interfaces methods, properties etc in a class which implements said interface why bother using the interface in the first place and simply just declare said mathods in the class and not bother with the interface declaration.

    I realise .NET only allows the inheritance of one class but could someone explain how I would inherit two "classes" into one base class using interfaces please (From a C# perspective but VB.NET examples are fine as well)

     

    Thanks

    Filed under: ,
  • Re: Strugglnig understanding the reason behind interfaces

    03-29-2008, 4:19 AM
    Answer
    • Star
      12,579 point Star
    • codeasp
    • Member since 06-16-2004, 9:19 PM
    • Posts 2,201
  • Re: Strugglnig understanding the reason behind interfaces

    03-29-2008, 4:27 AM
    Answer

    Hi,

    What I am having trouble understanding is why we do this

    Interfaces are a powerful programming tool because they let you separate the definition of objects from their implementation. Interfaces and class inheritance each have advantages and disadvantages, and you may end up using a combination of both in your projects.

    There are several other reasons why you might want to use interfaces instead of class inheritance:

    • Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

    • Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.

    • Interfaces are better in situations in which you do not have to inherit implementation from a base class.

    • Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

     http://msdn2.microsoft.com/en-us/library/3b5b8ezk.aspx

    realise .NET only allows the inheritance of one class but could someone explain how I would inherit two "classes" into one base class using interfaces please 
     

    C# supports single inheritance. It can inherit from one class, however it does supports multiple 'interface' inheritance:

    Eg:

    Single Inheritance

    public class A
    {
        public A() { }
    }

    public class B : A

    {
        public B() { }
    }

    Multiple Interface Inheritance

    interface IComparable
    {
        int CompareTo(object obj);
    }

    interface ISomethingElse
    {
        int EqualTo();
    }

    public class Z :  IComparable, ISomethingElse
    {
        public int CompareTo(object obj)
        {
            // implementation code goes here 
        }

    public int EqualTo()
        {
           
    // implementation code goes here 
        }

    }


    HTH,
    Suprotim Agarwal

  • Re: Strugglnig understanding the reason behind interfaces

    03-30-2008, 3:31 PM
    Answer
    • All-Star
      18,335 point All-Star
    • Svante
    • Member since 02-12-2007, 7:15 AM
    • Stockholm, Sweden
    • Posts 2,298
    • Moderator

    JohnCogan2:
    What I am having trouble understanding is why we do this. If you have to implmenet all the interfaces methods, properties etc in a class which implements said interface why bother using the interface in the first place and simply just declare said mathods in the class and not bother with the interface declaration.

    The use of an Interface enables disparate types to be treated similarily, although the implementations may vary widely. For example, the IEnumerable Interface defines the basic methods required for enumerating (stepping through all elements) a collection of whatever. This means that code can be programmed to use the interface, and will work regardless of being fed an array, a list, a sorted collection or whatever. This is a very powerful tool. It's about inheriting behavior - not implementation.

    Interfaces are best used when you have a "is also a" relationship, rather than "is a special kind of" relationship which is the best use for traditional base class implemenation inheritence.

    The whole point of an Interface is to define the contract, which may then be implemented in a variety of ways - all of which are hidden to the clients of the types implementing the interface. That is why it's meaningful to define the Interface and then implement all the methods.

    Base class inheritence,where code (implementation) is re-used should be reserved for specialization, not generalization. In other words, when you inherit code via base class inheritance, the derived class should refine and specialize the behavior of the base class  - not extend it.

    To extend behavior, other patterns such as composition (wrapping) are more suitable.

    Svante
    AxCrypt - Free Open Source File Encryption & Online Password Manager - http://www.axantum.com
    [Disclaimer: Code snippets usually uncompiled, beware typos.]
    ______
    Don't forget to click "Mark as Answer" on the post(s) that helped you.
  • Re: Strugglnig understanding the reason behind interfaces

    03-31-2008, 5:34 AM
    • Member
      125 point Member
    • JohnCogan2
    • Member since 03-07-2006, 10:44 AM
    • Posts 35

    Ok its quite possible I am been quite dim on this subject, but in your given example Suprotim, if I was writing the code I'd simply do the following:

    public class Z
    {
        public int CompareTo(object obj)
        {
            // implementation code goes here 
        }

    public int EqualTo()
        {
           
    // implementation code goes here 
        }

    }

    The reasons I'd do it this way (Which I am sure is totally incorrect when compared to your example) is because I'd look at the code and say to myself, "Well Class Z" is going to have to implement the methods anyway so I'll cut out the interfaces and just write the methods directly into the class.

    I think I am not seeing the reasons behind a "contract" when the class using an interface has to write the "working" code of the interface methods anyway. To me it seems like there is no point in doing that UNLESS the interface is used to make sure multiple classes referencing similair methods adhere to using the same method names.

    Again my apologies for my "dim-witted" approach to this, but I want to nail interfaces to the ground in my mind.

    Thanks for all your replies and time.

    John

  • Re: Strugglnig understanding the reason behind interfaces

    03-31-2008, 5:45 AM
    • All-Star
      18,335 point All-Star
    • Svante
    • Member since 02-12-2007, 7:15 AM
    • Stockholm, Sweden
    • Posts 2,298
    • Moderator

    JohnCogan2:
    "Well Class Z" is going to have to implement the methods anyway so I'll cut out the interfaces and just write the methods directly into the class.

    Yes - but other clients of the class (in this case the .NET framework) won't then know that the class in fact implements IComparable - and won't be able to use the method you implemented. You just have a method named CompareTo, but you have not implemented the interface.

    Large parts of the framework requires or can use the fact that a class implements IComparable - so if you want that type of functionality it's a good idea to implement the specific interface, which means that other code can really depend on your class implementing the right semantics and can thus use the method in question.

    Svante
    AxCrypt - Free Open Source File Encryption & Online Password Manager - http://www.axantum.com
    [Disclaimer: Code snippets usually uncompiled, beware typos.]
    ______
    Don't forget to click "Mark as Answer" on the post(s) that helped you.
  • Re: Strugglnig understanding the reason behind interfaces

    03-31-2008, 6:29 AM

    A very interesting piece of text that i read some time ago written by a Microsoft employee API Design Myth: Interface as Contract, which clarifies this 'myth' by saying that "Interfaces don't specify a contract. Rather, they simply specify the syntax". This blogpost also explains the difference in terms of semantics and syntax. If semantics has to be enforced, a base class should be used. Interesting!! :)

    HTH,
    Suprotim Agarwal 

     

  • Re: Strugglnig understanding the reason behind interfaces

    03-31-2008, 6:46 AM
    • All-Star
      18,335 point All-Star
    • Svante
    • Member since 02-12-2007, 7:15 AM
    • Stockholm, Sweden
    • Posts 2,298
    • Moderator

    Suprotim Agarwal:
    "Interfaces don't specify a contract. Rather, they simply specify the syntax". 

    True enough from a language perspective. However, it's aking to saying 'a for loop does not signify iteration, it just specifies a syntax'. There's no requirement to use a for loop for iteration. It's just provides a syntactical construct. However, the syntax in question is well suited for the purpose it was designed for. Interfaces provides you the tool to specify the syntax for a given behavior in a convenient way.

    Interfaces indeed do not enforce behavior (semantics). However, they do provide a way of specifying a common syntax for invoking a behavior - but they do not enforce it. But, an interface that in fact does not implement it's contract properly has a bug, something all software has. Properly used, interfaces will still reduce the total number of bugs in your code by making the intent, use and reuse possibilities clearer.

    The base class approach will not eliminate bugs. But it will concentrate them to fewer places, which is a good thing.

    There are unfortunately many things you can't do conveniently and safely if you only use base classes and not interfaces.

    The best way is to combine the two approaches, and provide (abstract) base classes for common behavior when appropriate and then implement interfaces by deriving specialized versions of these base classes and using composition (wrapping) to implement the required methods of the interface.

    Svante
    AxCrypt - Free Open Source File Encryption & Online Password Manager - http://www.axantum.com
    [Disclaimer: Code snippets usually uncompiled, beware typos.]
    ______
    Don't forget to click "Mark as Answer" on the post(s) that helped you.
  • Re: Strugglnig understanding the reason behind interfaces

    03-31-2008, 8:01 AM

    The best way is to combine the two approaches, and provide (abstract) base classes for common behavior when appropriate and then implement interfaces by deriving specialized versions of these base classes and using composition (wrapping) to implement the required methods of the interface.

    Yes..Can't agree more. There are also instances when interface do not fit the bill. For eg: If I anticipate that I may need to add new methods in future to extend functionality, I have to go in and decide to use an abstract class. So I could always add this 'new method' with some default implementation to the abstract class and it won't break the behaviour of the clients. However If i had to do the same with an interface and add a new method to it, I couldn't do it without breaking the behaviour of the class that implemented the interface.

    HTH,
    Suprotim Agarwal

Page 1 of 1 (9 items)