Understand Core of Dependency Injection Loose/Tight couple.
2 min readAug 29, 2024
To understand dependency injection concept properly, We need to understand difference between loose coupling and tight coupling.
Tight coupling:
📌Tight coupling occurs when two classes or modules are highly dependent on each other.
📌Changes in one class often require changes in the other,
📌making the code harder to maintain.
Loose coupling:
📌Loose coupling is when classes or modules are less dependent on one another.
Tight coupling example:
class PetrolEngine {
start() {
return "Petrol engine started with a roar";
}
}
class ElectricEngine {
start() {
return "Electric engine started silently";
}
}
class Car {
private engine: PetrolEngine; // Tightly coupled to PetrolEngine
constructor() {
this.engine = new PetrolEngine(); // Directly instantiating PetrolEngine
}
startCar() {
return this.engine.start();
}
}
const myCar = new Car();
console.log(myCar.startCar()); // Output: Petrol engine started with a roar
Problem with Tight Coupling
- If you want to switch from
PetrolEngine
toElectricEngine
, you would need to modify theCar
class:
Example of loose coupling:
// Define an interface for engines
interface IEngine {
start(): string;
}
// Implement the IEngine interface in the PetrolEngine class
class PetrolEngine implements IEngine {
start(): string {
return "Petrol engine started with a roar";
}
}
// Implement the IEngine interface in the ElectricEngine class
class ElectricEngine implements IEngine {
start(): string {
return "Electric engine started silently";
}
}
// Car class is loosely coupled to IEngine, not to a specific engine type
class Car {
private engine: IEngine;
constructor(engine: IEngine) { // Dependency injection
this.engine = engine;
}
startCar(): string {
return this.engine.start();
}
}
// Create instances of PetrolEngine and ElectricEngine
const petrolEngine = new PetrolEngine();
const electricEngine = new ElectricEngine();
// Inject PetrolEngine into the Car
const petrolCar = new Car(petrolEngine);
console.log(petrolCar.startCar()); // Output: Petrol engine started with a roar
// Inject ElectricEngine into the Car
const electricCar = new Car(electricEngine);
console.log(electricCar.startCar()); // Output: Electric engine started silently
Benefits of Loose Coupling
- Flexibility: The
Car
class can now work with any engine that implements theIEngine
interface, without modification.
Summary
- Tight Coupling: The
Car
class was tightly coupled to a specific engine type (PetrolEngine
), making it inflexible and difficult to maintain. Changing the engine type required modifying theCar
class. - Loose Coupling: By using an interface (
IEngine
) and dependency injection, theCar
class became loosely coupled to the engine. It can now work with any engine that implementsIEngine
, making the design more flexible, maintainable, and testable.
Hit Clap if you learnt something today !!