Understanding Interfaces Via Loose Coupling And Tight Coupling

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

  1. public class CustomerRepository {  
  2.     private readonly Database database;  
  3.     public CustomerRepository(Database database) {  
  4.         this.database = database;  
  5.     }  
  6.     public void Add(string CustomerName) {  
  7.         database.AddRow("Customer", CustomerName);  
  8.     }  
  9. }  
  10. public class Database {  
  11.     public void AddRow(string Table, string Value) {}  
Loose Coupling

 

  1. public class CustomerRepository {  
  2.     private readonly IDatabase database;  
  3.     public CustomerRepository(IDatabase database) {  
  4.         this.database = database;  
  5.     }  
  6.     public void Add(string CustomerName) {  
  7.         database.AddRow("Customer", CustomerName);  
  8.     }  
  9. }  
  10. public interface IDatabase {  
  11.     void AddRow(string Table, string Value);  
  12. }  
  13. public class SqlDatabase: IDatabase {  
  14.     public void AddRow(string Table, string Value) {  
  15.         //Logic to add new customer in sql table  
  16.     }  
  17. }  
  18. public class XMLDatabase: IDatabase {  
  19.     public void AddRow(string Table, string Value) {  
  20.         //Logic to add new customer in XML Document  
  21.     }  
  22. }