Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of abstract class over interface

Tags:

c#

I got the following statement from an MSDN article. It says that the abstract classes have an advantage over interfaces because it is possible to alter an abstract class to add new members. Doesn't altering the abstract class really make the classes inheriting from it unstable? Or can any one please explain what is their point here?

Do favor defining classes over interfaces.

In later versions of your library, you can safely add new members to classes; you cannot add members to interfaces without breaking existing code.

like image 228
logeeks Avatar asked Dec 07 '22 16:12

logeeks


2 Answers

Say you have an interface

public interface Animal 
{
     void Sleep();
}

you release your library and you find out you need to add a property to the interface.

public interface Animal 
{
     int Age{get;set;}
     void Sleep();
}

All the code that every one wrote against the first version of the interface would no longer compile forcing an upgrade. If you released the first version with this abstract class.

public abstract class Animal 
{
    public abstract  void Sleep();
} 

Now you need to add another property

public abstract class Animal
{
    public virtual int Age{get;set;}
    public abstract  void Sleep();
} 

In this case there is no need for users to change there code.

like image 200
rerun Avatar answered Dec 28 '22 22:12

rerun


It's not to be taken too strictly. Programming through interfaces (as contracts) is really the best way to decouple your application. For example, creating a wrapper around an interface is very easy, while a class doesn't even have to have a single virtual method.

Additionally, the article doesn't even seem to compare abstract classes to interfaces (because it only mentions them in the next "guideline"), but all classes in general over interfaces. So, it's a rather fuzzy guideline, if you ask me.

It might make sense exclusively with the problem stated: changing an interface breaks all implementations, while adding members to a class doesn't. On the other hand, if you change a method's signature, you won't be very lucky with classes either. From a security point of view, abstract classes do provide a way to make sure that your library always exposes its own functionality to callers, allowing modifications only where you want them. With interfaces, you can pass pretty much any code which satisfies the contract.

like image 32
Groo Avatar answered Dec 29 '22 00:12

Groo