Dependency Injection - Part Two (Five Reasons To Write Loosely Coupled Code)

In the previous article, we studied a tightly coupled application and listed out the problems we found with the same. In this article, we will explore how to write loosely coupled code that helps us in keeping our applications easy to write, test, and maintain.


A loosely coupled application has good isolation among its classes, modules, and assemblies. Therefore, if we make a change to one part of the application, we only need to update the relevant modules. We do not need to make changes throughout the application.

With respect to dependency injection, a dependent class must be loosely coupled with its dependency classes such that the dependent class doesn't have to worry about instantiating its dependencies. Instead, the user of the dependent class shall provide all its dependencies while instantiating it.

If we are using DI containers, we need to register the types with the container. As well, the container will instantiate the dependencies whenever and wherever required, by the dependent class.

Why loosely coupled code?
  1. Extensible
    Loose coupling helps us write extensible code that can respond quickly to the new requirements. Therefore if we need to swap out an existing feature, one with different functionality, this becomes very easy to do. Also, while adding a new feature, we can simply plug it into our existing application.

  2. Unit Testing
    If the application is loosely coupled and designed for unit testing, it is technically possible to unit test almost any piece of code. However, not designing the code efficiently for unit testing can cause some very complicated unit tests. We always want a code that is easy to understand and easy to test.

  3. Late Binding
    Loose Coupling also helps us achieve dynamic loading of modules when we run our application. This allows us to ship different components to different clients, and our application picks up the right ones when deployed.

  4. Parallel Development
    If one module doesn't directly depend upon another module, instead is loosely coupled, we can have different members of the team working on these modules at the same time. Also, changes to one module do not directly impact the other module.

  5. Maintainability
    A good code is one that is easy to maintain, and loose coupling helps us write one. If we have different parts of code isolated from each other, we know where we need to fix bugs or make any updates. We do not have to worry about making similar changes in other parts of the application. We can directly plug in our latest code and deploy it.


In this article, we briefly touched the important aspects that we must take care of while designing our application. I hope this article gives us a fair idea of how loose coupling the code makes our application extensible, maintainable, and easy to unit test.