Familiar with "tight coupling" in OOPs? It's a common issue where classes become overly interdependent, making code changes cumbersome and error-prone. Imagine updating one class and having to revise multiple others due to tight dependencies.
This is how a tightly coupled code looks like:
Here, the direct instantiation of Engine class within the constructor of Car class creates a strong dependency between the two classes.
The problem encountered in the above code can be solved using Dependency injection in Spring and by promoting the use of Interfaces.
METHOD 1: Dependency injection using constructor injection
Problem ❌: Tight coupling occurs when one class directly instantiates another class, using the “new” keyword
Solution 💡: Use Dependency injection to pass dependency from external sources, highly used in Spring . In the below figure the engine object is being passed as the parameter to the constructor from an external source.
METHOD 2: Using interfaces
Problem ❌: Classes depending on concrete implements rather than interfaces, causes tightly coupled relationship between them. To say, if the type of engine to be used by a car is changed the whole code has to be re written again.
Solution 💡: Use interfaces instead of using concrete classes, this gives more flexibility to a code.
Follow Me for such contents!
Happy Learning :)