Monday, 25 March 2013

 When to prefer Interfaces or Abstract classes?


When to prefer an interface:-
           
 Lets say you have an interface for a Director and another interface for a Actor.
interface IActor{
   void DoAct();
}
interface IDirector{
   void DoDirect();
}
     In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:
interface IActorDirector :IActor, IDirector{
...
}
 
  We know that c# doesn't support mulitple inheritance.So we can achieve 
muliple inheritance in the form of multiple interface implementaion. 
 
When to prefer an Abstract class:-
    
      Abstract classes allow you to provide default functionality for the subclasses. If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class.Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.
 
 General Rule:-
   1.If you are creating something that provides common functionality to unrelated classes, use an interface.
   2.If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

No comments:

Post a Comment