Middle
How do you understand the principle of dependency inversion (DIP)? How does it differ from Dependency Injection?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles. It states:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
In other words, instead of a class directly creating or using specific implementations, it works through abstractions (e.g., interfaces), which increases flexibility and testability.
Dependency Injection (DI) is a pattern or technique that implements the dependency inversion principle. DI means dependencies (objects needed by a class) are passed to it from outside (via constructor, setter, or interface), rather than created inside the class.
Thus:
- DIP is a design principle that guides how to build dependencies between modules.
- DI is a way to implement this principle in practice.
Example:
interface Service {
void execute();
}
class ServiceImpl implements Service {
public void execute() {
System.out.println("Executing service");
}
}
class Client {
private Service service;
// Dependency is injected via constructor
public Client(Service service) {
this.service = service;
}
public void doWork() {
service.execute();
}
}
// Usage
Service service = new ServiceImpl();
Client client = new Client(service);
client.doWork();
Here, Client depends on the abstraction Service, and the concrete implementation is passed from outside — this is DIP and DI.