Classes versus interfaces

What came first, the chicken or the egg? Should I pass a class or an interface? People will fight over these topics until the cows come home. So why don't we just get knee deep into it and put a stake in the ground. For us, let's define an interface type as a specification of a protocol, potentially supported by many object types. Should we use base classes instead of interfaces whenever possible? From a versioning perspective, classes are more flexible than interfaces. With a class, we can ship version 1.0 and then, in version 2.0, add a new method to the class. As long as the method is not abstract, any existing derived classes continue to function unchanged.

Another potential hazard for us is that because interfaces do not support implementation inheritance, the pattern that applies to classes does not apply to interfaces. Adding a method to an interface is equivalent to adding an abstract method to a base class; any class that implements the interface will break because the class does not implement the new method. In many environments, maintaining backward compatibility is of paramount importance.

Let us say that interfaces are appropriate in the following situations:

  • Several unrelated classes want to support a protocol
  • These classes already have established base classes (for example, some are user interface controls, and some are XML web services)
  • Aggregation is not appropriate or practical

In all other situations, class inheritance is a better model for what we are trying to achieve. Or is it?

If you've been paying intention (pop quiz time), an interface is basically a way of getting around the lack of inheritance in C#, right? What do we mean by lack of inheritance? In a nutshell, in C#, you cannot inherit from multiple classes, but you can inherit from multiple interfaces. Interfaces can also inherit and implement other interfaces as well. Hmmm, this could be the right choice for us.

An interface is a contract, plain and simple. Any implementing class is required to implement everything in the interface. This includes properties, methods, and events. An interface contains only the signatures of the functionality, not the complete concrete implementation. This provides loose coupling, easier maintainability, makes our code more scalable, and makes code reuse much more accessible. The implementation is separate from the interface. This also makes it much easier to create plug and play architectures and implement IoC/Dependency Injection (DI) in your applications.

So what will we do? We will actually implement a mixture of both, inheriting from interfaces when possible and from concrete base classes if the proverbial shoe fits.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset