Friday 27 April 2012

When to use Interface


Interfaces are useful in order to add a level of abstraction early on in the design process. It will benefit the modularity of your code. If you have a big enough project (one that warrants using mocking) interfaces are useful, though for small projects this is most likely overkill. They can be used more than they need to be certainly, but if you take to heart the following guidelines you will know when to use inheritance and when to use an interface. Your code reusability and scalability will increase greatly when interfaces are used where appropriate!
The old explanation of when to inherit works nicely:
  • Is a - inheritance
    Your class is a subclass of a more generalized class, e.g. HouseCat inherits from Felinebecause a house cat "is a" feline.
  • Has a - member field
    LittleGirl has a cat, so obviously she should not be a subclass to HouseCat (she is not acat). It is best that she "has aHouseCat member field.
    class LittleGirl
    {
        int age;
        string name;
        HouseCat pet;
    }
    
  • Performs - interface
    Interfaces should be used when a class or group of classes all have similar functionality, but when there is no obvious line of inheritance. Think of them as a certificate that says "this object performsthis functionality."
    For example, a HouseCat might inherit from Feline, but implement the ICanHasCheeseburgers(or ICanHazChzbrgrsPlz) interface. That way you have a BurgerJoint class with a methodpublic CheeseBurger Serve(ICanHasCheeseburgers patron) and be able to pass eitherHumans or HouseCats to the Serve method in order to feed them a Cheeseburger.
    This is useful because HouseCat does not inherit from Person nor vice versa. However, they both perform acts involving CheeseBurgers

No comments:

Post a Comment