FeaturedIT topics

How not to use interfaces in C#

When designing an application, you will often need to use interfaces and abstract classes. This article discusses some common examples of “interface abuse” and the strategies we can use to avoid them. It also discusses what is meant by the tenet, “program to an interface and not to an implementation.”

What are interfaces?

First off, let’s get an understanding of interfaces and why they are needed in programming. An interface is strictly a contract; it doesn’t have any implementation. An interface contains only member declarations. You can have method declarations but not definitions. The members declared in an interface should be implemented in the types (classes and structs) that extend or implement the interface. An interface cannot contain fields. An interface cannot be serialized because it cannot have data members. As I said, an interface can have only declarations and not definitions.  

Avoid making changes to interfaces 

A class or a struct that extends an interface should implement all of its members. If the implementation changes, your code will still work. However, if the contract, i.e., the interface, changes, then you’ll have to change the implementations of all types that extend the interface. In other words, any change to the interface will impact all of the types that extend the interface. The types extending the interface must adhere to the contract. So, use interfaces only when you rarely need to change them. Also, it’s generally better to create a new interface than change an existing one. 

Program to an interface, not to an implementation

Related Articles

Back to top button