08 June 2015

Difference between tight coupling and loose coupling

If you are new to software design and if you are wondering when people say “this is a good loosely coupled design” and this “this is tightly coupled design, change it” continue reading the post. In this post let’s talk about “what is tight coupling”, “what is loose coupling” in software design and discuss difference between them.

Let’s consider you are working on a developing Graphical design application (similar to Photoshop, Corel Draw). As a graphics design app, your asked to provide the below capabilities.

Allows user to choose shapes.

Allows you to print your drawing.

Allows you to save your changes into database

To understand coupling between classes, let's consider an example and implement the 3rd point, “Saving into database”.

To do this let’s create repository class to save into SQL SERVER database.

With the above implementation everything is working as expected when using SQL SERVER as a database. Your boss is happy and hence you are happy!

One fine day, one of your potential customer willing to buy your graphics design application. But the customer doesn’t have SQL Server license instead has the ORACLE database. But your application design is supporting only SQL Server database and your gut feeling is you can easily add support for Oracle DB.

Then you will start looking into the code to realize that it’s an uphill task to add any new database support. Entire application has been hardcoded to work just with SQL Server!.

It means your application has been hardcoded to work only with SQL Server as DB.

This called DIRECT COUPING. There is direct coupling your application and SQL SERVER DB.

With this approach to design you cannot easily replace components your application is using

Now having understand the problems of direct coupling let’s talk about how to eliminate direct coupling.

Your application isn’t hardcoded to use SQLRepository anymore. Now your design flexible to any kind of database repository which implements the IRepository interface. This means your application loosely coupled with database interaction via the interface.

Advantage of loosely coupled design

If in future you want to add support for new database, say MySQL database, then you just create MySQLRepository class implementing the interface.

This doesn’t need changes to your existing application code logic, so you save on regression effort required to support new databases.

This means that just add a new repository and test that alone and use it with the application. It’s just as simple as that. With this loosely coupled design approach, your application development will be faster.

With loosely coupled design your application has dependency on a class implementing IRepository. This can be solved by using dependency injection.