While attending the C# Corner Chapter @ Chandigarh, there was a query from one of the attendees about the use of Interfaces.
So, I decided to write an article on the basic usage of Interfaces in C#. To understand this, first, we need to understand the concept of Tight coupling and Loose coupling.
Tight Coupling is when in a group, classes are highly dependent on one another.
This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.
Loose Coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.
A loosely-coupled class can be consumed and tested independently of other (concrete) classes.
Interfaces are powerful tools used for decoupling. Classes can communicate, through interfaces, to other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.
Tight Coupling
- public class CustomerRepository {
- private readonly Database database;
- public CustomerRepository(Database database) {
- this.database = database;
- }
- public void Add(string CustomerName) {
- database.AddRow("Customer", CustomerName);
- }
- }
- public class Database {
- public void AddRow(string Table, string Value) {}
- }
Loose Coupling
- public class CustomerRepository {
- private readonly IDatabase database;
- public CustomerRepository(IDatabase database) {
- this.database = database;
- }
- public void Add(string CustomerName) {
- database.AddRow("Customer", CustomerName);
- }
- }
- public interface IDatabase {
- void AddRow(string Table, string Value);
- }
- public class SqlDatabase: IDatabase {
- public void AddRow(string Table, string Value) {
-
- }
- }
- public class XMLDatabase: IDatabase {
- public void AddRow(string Table, string Value) {
-
- }
- }