Junior — Middle
Explain the concept of dependency injection in the context of SOLID principles.
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a principle where an object receives its dependencies from outside rather than creating them itself. This helps adhere to the Single Responsibility Principle from SOLID, as the class is not responsible for creating dependencies.
Also, DI promotes the Dependency Inversion Principle, as classes depend on abstractions rather than concrete implementations.
Example: instead of creating a service object inside the class, we pass it through the constructor or a setter.
public interface Service {
void execute();
}
public class ServiceImpl implements Service {
public void execute() {
System.out.println("Executing service");
}
}
public class Client {
private Service service;
// Dependency injection 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();
Thus, DI improves modularity, testability, and code flexibility.