When I started working with larger applications, I noticed a common problem: some services became tightly connected to specific technologies.
For example, a business service might directly create a MongoDB repository. At first, this looks completely fine. The code works, and there is nothing obviously wrong with it.
But as the application grows, things become harder to change.
What happens if we move from MongoDB to PostgreSQL? What if we want to use a different data source? What if we want to test the business logic without connecting to a real database?
This is where the Dependency Inversion Principle (DIP) becomes useful.
DIP is the D in SOLID, and its main idea is simple:
High-level code should not depend directly on low-level implementation details. Both should depend on an abstraction.
DIP is also often discussed together with Dependency Injection (DI), but they are not the same thing. DIP is a design principle, while DI is a technique for providing dependencies to an object.
What Is a Dependency?
Before understanding dependency inversion, let's understand what a dependency is.
A dependency is simply something that a piece of code needs to perform its job.
For example:
class UserService {
constructor() {
this.repository = new MongoUserRepository();
}
}
Here, UserService depends on
MongoUserRepository.
Why?
Because UserService directly creates and uses it.
The dependency relationship looks like this:
UserService
|
↓
MongoUserRepository
At first, this may not seem like a problem.
But now imagine that the application needs to move from MongoDB to PostgreSQL.
We may need to modify UserService even though the actual
business logic of UserService has not changed.
That is the kind of coupling DIP tries to reduce.
The Problem With Direct Dependencies
Let's look at a simple example.
class MongoUserRepository {
findUser(id) {
console.log(`Finding user ${id} from MongoDB`);
}
}
class UserService {
constructor() {
this.repository = new MongoUserRepository();
}
getUser(id) {
return this.repository.findUser(id);
}
}
There are two classes here:
- UserService — contains the application/business logic.
- MongoUserRepository — handles database-specific work.
The problem is that UserService knows about the concrete
implementation:
new MongoUserRepository()
This means the high-level UserService is directly connected
to a low-level database detail.
If the database implementation changes, UserService may also
need to change.
How DIP Changes the Design
Instead of making UserService depend directly on
MongoUserRepository, we introduce an
abstraction.
The abstraction represents what UserService actually needs.
In this example, the requirement is simple:
"I need something that can find a user."
So we can think of the abstraction as a
UserRepository.
UserRepository
/ \
/ \
↓ ↓
MongoDB PostgreSQL
Repository Repository
Now UserService does not need to know which database is being
used.
A Simple JavaScript Example
JavaScript does not require us to declare an interface like Java or TypeScript does, but we can still design our code around a clear contract.
The contract in this example is:
UserRepository must provide findUser()
Our service can then look like this:
class UserService {
constructor(userRepository) {
this.userRepository = userRepository;
}
getUser(id) {
return this.userRepository.findUser(id);
}
}
And our MongoDB implementation can provide that behavior:
class MongoUserRepository {
findUser(id) {
console.log(`Finding user ${id} from MongoDB`);
}
}
We can also create another implementation:
class PostgreSQLUserRepository {
findUser(id) {
console.log(`Finding user ${id} from PostgreSQL`);
}
}
Now UserService does not need to know whether the data comes
from MongoDB or PostgreSQL.
We can decide which implementation to use outside the service:
const repository = new MongoUserRepository();
const userService = new UserService(repository);
userService.getUser(101);
Later, we could use:
const repository = new PostgreSQLUserRepository();
const userService = new UserService(repository);
userService.getUser(101);
The important part is that UserService itself did not change.
So Where Is the "Inversion"?
This is the part that confused me initially when learning DIP.
Before applying DIP, the dependency looks like this:
UserService
|
↓
MongoUserRepository
The high-level business logic depends directly on the low-level implementation.
After applying DIP, the relationship becomes conceptually:
UserRepository
↑ ↑
| |
| |
UserService MongoUserRepository
Both sides depend on the abstraction.
This is the "inversion" in Dependency Inversion Principle. Instead of high-level policy depending directly on low-level details, the dependency relationship is organized around an abstraction closer to the high-level requirement.
In simple terms:
Before:
Business Logic → Database Implementation
After:
Business Logic → Repository Abstraction ← Database Implementation
That change is the heart of DIP.
What Are High-Level and Low-Level Modules?
These terms can sound complicated, but the idea is fairly simple.
High-Level Module
A high-level module contains the important business rules or application logic.
For example:
UserService
OrderService
PaymentService
CheckoutService
These classes describe what the application is trying to do.
Low-Level Module
A low-level module usually deals with implementation or infrastructure details.
For example:
MongoDB
PostgreSQL
Redis
File System
SMTP
External APIs
These components describe how something is technically done.
DIP says that high-level modules should not be directly tied to these low-level implementation details. Instead, both sides should work through suitable abstractions.
What Is an Abstraction?
An abstraction is a way of describing what something does without making the user of it care about how it does it.
For example, UserService doesn't really care whether a user
is retrieved from:
- MongoDB
- PostgreSQL
- MySQL
- An API
- An in-memory data store
- A fake repository used for testing
It only needs something that can provide the required user data.
So instead of thinking:
"I need MongoDB."
the service should think:
"I need a user repository."
That distinction is important.
The abstraction should represent a meaningful requirement of the higher-level code, rather than simply creating an abstraction for every concrete class.
DIP and Dependency Injection Are Not the Same
This is one of the most common points of confusion.
They are related, but they are different concepts.
Dependency Inversion Principle
DIP tells us how dependencies should be designed.
The main idea is:
Depend on abstractions rather than concrete implementation details.
Dependency Injection
DI is a technique for providing those dependencies from outside.
For example:
const repository = new MongoUserRepository();
const userService = new UserService(repository);
Here, MongoUserRepository is supplied to
UserService from outside.
That is Dependency Injection.
A simple way to remember it is:
DIP = How should the dependency relationship be designed?
DI = How do we provide the dependency?
DI can help implement DIP, but simply injecting a concrete class does not automatically mean the code follows DIP.
For example:
class UserService {
constructor(mongoRepository) {
this.repository = mongoRepository;
}
}
The dependency is injected, but the service is still explicitly designed around MongoDB.
So:
Injection alone does not automatically mean Dependency Inversion.
DIP Makes Testing Easier
Another useful benefit of this design is testing.
Imagine UserService directly creates a MongoDB repository:
class UserService {
constructor() {
this.repository = new MongoUserRepository();
}
}
Testing UserService now involves the concrete database
implementation.
Instead, we can provide a simple fake repository:
class FakeUserRepository {
findUser(id) {
return {
id,
name: "Test User"
};
}
}
Then:
const repository = new FakeUserRepository();
const userService = new UserService(repository);
const user = userService.getUser(101);
console.log(user);
The business logic can now be tested without requiring the real database.
DIP does not magically make code testable, but depending on an appropriate abstraction can make it easier to substitute implementations during testing.
What If We Change the Database?
Suppose the application initially uses MongoDB.
UserService
↓
MongoUserRepository
Later, the project moves to PostgreSQL.
With DIP, we can introduce:
class PostgreSQLUserRepository {
findUser(id) {
console.log(`Finding user ${id} from PostgreSQL`);
}
}
Then:
const repository = new PostgreSQLUserRepository();
const userService = new UserService(repository);
The implementation changed, but the business service remained the same.
That's one of the main advantages of separating business rules from implementation details.
When Should You Use DIP?
DIP becomes especially useful when a project has dependencies such as:
- Databases
- Payment gateways
- Email services
- External APIs
- File storage
- Cloud services
- Message queues
- Third-party services
For example:
OrderService
↓
PaymentGateway
↑
|
StripePaymentGateway
RazorpayPaymentGateway
OrderService should care about the payment operation it needs,
rather than being tightly coupled to one specific payment provider.
This makes it easier to replace implementations when the architecture actually requires it.
When You Don't Need to Overuse DIP
DIP does not mean that every class needs an interface or abstraction.
For a small application, creating multiple interfaces and classes for every simple operation can make the code more complicated rather than simpler.
For example, if a simple utility has no meaningful alternative implementation and there is no architectural reason to abstract it, adding an abstraction just because it is "SOLID" may be unnecessary.
The goal is not:
More interfaces = Better code
The goal is:
Better separation between important business logic
and implementation details
Use abstractions where they provide a meaningful boundary.
A Simple Way to Remember DIP
Think about the difference between these two designs.
Without DIP
UserService
↓
MongoDB
The business logic knows about the database.
With DIP
UserRepository
↑ ↑
| |
UserService MongoDB Repository
The business logic depends on what it needs, not on the specific technology that provides it.
The Main Idea
If I had to explain Dependency Inversion Principle in one sentence, I would put it this way:
Your high-level business logic should depend on an abstraction that represents what it needs, rather than directly depending on a low-level implementation.
For example:
Don't think:
UserService → MongoDB
Think:
UserService → UserRepository ← MongoDB
The database is an implementation detail.
The repository represents the capability that the business logic actually needs.
That separation can make the system easier to change and can make testing and replacement of implementations simpler.
Final Takeaway
The Dependency Inversion Principle can sound complicated because of the word "inversion."
But the core idea is straightforward:
- Identify your high-level business logic.
- Identify the low-level implementation details it currently depends on.
- Define an abstraction around what the high-level code actually needs.
- Make the high-level code depend on that abstraction.
- Make the low-level implementation follow that abstraction.
- Use Dependency Injection to provide the actual implementation.
The important thing to remember is that DIP is about the design of dependencies, while Dependency Injection is one technique for supplying those dependencies.
Once you understand that difference, the D in SOLID becomes much easier to understand.
SOLID Series
- S — Single Responsibility Principle
- O — Open/Closed Principle
- L — Liskov Substitution Principle
- I — Interface Segregation Principle
- D — Dependency Inversion Principle
Previous: Interface Segregation Principle
Next: Coming soon