🔹 Dependency Injection
**Dependency Injection (DI)** is a design pattern used to achieve **Inversion of Control (IoC)** in object-oriented programming. It allows a class to receive its dependencies from an external source rather than creating them internally.
📌 Why Use Dependency Injection?
Dependency Injection helps in **loosely coupling** components, making code more modular, testable, and maintainable.
- ✅ **Improves Code Maintainability** – Reduces hard dependencies between classes.
- ✅ **Enhances Testability** – Makes it easier to write unit tests using mock dependencies.
- ✅ **Promotes Reusability** – Decouples implementation details from class behavior.
💡 Real-Life Example
Consider a **Car** that needs an **Engine**. Instead of the Car creating an Engine internally, we inject an Engine dependency from outside.
🖥️ Dependency Injection in Java (Spring Framework)
Spring's **@Autowired** annotation injects dependencies automatically.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
class Engine {
public void start() {
System.out.println("Engine started...");
}
}
@Component
class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
public void drive() {
engine.start();
System.out.println("Car is driving...");
}
}
🖥️ Dependency Injection in Python
In Python, DI can be implemented using constructor injection.
class Engine:
def start(self):
print("Engine started...")
class Car:
def __init__(self, engine):
self.engine = engine
def drive(self):
self.engine.start()
print("Car is driving...")
engine = Engine()
car = Car(engine)
car.drive()
🎯 Summary
**Dependency Injection** is a core principle in modern software design that **reduces tight coupling**, makes testing easier, and enhances **code reusability and maintainability**.