DEV Community

Priyanka-Chettri
Priyanka-Chettri

Posted on

1 1

Overcoming Tight Coupling In OOPs With Effective Solutions

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.

Tight coupled code

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.

Solving tight coupling using dependency injection

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.

Solving tight coupling using Interface

Follow Me for such contents!
Happy Learning :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more