Last updated on April 1, 2019
In the last post, we analyzed a tightly coupled application and listed out the problems we found with the same. In this post, we will explore, how writing loosely coupled code helps us 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. And, the container will instantiate the dependencies whenever and wherever required by the dependent class.
Why loosely coupled code?
Loose coupling helps us write extensible code. Code that can respond quickly to new requirements. So that, 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 plugin it in to 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 end up with 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.
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.
I hope this gives us a fair idea about how loose coupling the code makes our application extensible, maintainable and easy to unit test. It’s always great to have feedback from the readers. Your valuable feedback, question, or comments about this article are always welcome.