coupling

What Is Coupling?

 

Today and tomorrow we’ll look at Coupling and Cohesion. You might have heard that Coupling is bad and Cohesion is good. Yes, that is true. These two concepts are mirror opposites of one another:

Coupling – Code that does not belong together 

Cohesion – Code that belongs together

If we achieve low Coupling and high Cohesion, our software should be easier to understand and simpler to change than vice versa; high Coupling and low Cohesion. 

Say, in high-level business logic we access a SQL Server database in this way:

  var database = new SqlServerDataAccess(connectionString);
  var orders = database.GetCustomerOrders(customerId);

In this example, the business logic has a dependency on data access. In the first line, SqlServerDataAccess is directly instantiated:

   var database = new SqlServerDataAccess(connectionString);

That is a problem. Why?

  1. Hard to change. If we wanted to change our data access to a MongoDB database, we could not easily do so. We are already committed to SqlServerDataAccess.
  2. Hard to unit test. We will have a hard time unit testing the business logic code without actually making calls to the SQL Server database. Unit tests don’t make calls to databases.

We have an undesirable dependency from the business logic to SQL Server data access code. We say that the business logic is coupled to the data access.

How do we identify Coupling?

Look for code that changes for different reasons

Business logic changes when business stakeholders change their minds regarding workflows. Data access changes when database admins and developers want to store or retrieve data differently. It doesn’t make sense to have the business logic depend on DBAs and developers’ whims.

Tomorrow we’ll explore Coupling’s polar opposite: Cohesion.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply