Skip to content

Dependency

Dependency is a relationship where one class (the client) depends on another class (the supplier) because it uses that class in some way. If the supplier changes, the client may need to change too.

Dependency is the weakest form of relationship between classes.


A Customer depends on a Restaurant:

  • Customer calls the restaurant to place an order
  • Customer doesn’t own the restaurant
  • Customer just needs the restaurant’s service temporarily

If the restaurant changes its menu, the customer may need to change their order.


TypeDescriptionExample
Method parameterPassed into a methodfunction process(paymentService)
Local variableCreated inside a methodconst email = new EmailService()
Return typeMethod returns an instancegetDatabase(): Database
Static method callCalling static methodsLogger.log("message")

Dependency Injection is a technique where dependencies are “injected” into a class from outside.

class OrderService {
constructor() {
this.logger = new Logger();
this.emailService = new EmailService();
this.paymentService = new PaymentService();
}
}
class OrderService {
constructor(logger, emailService, paymentService) {
this.logger = logger;
this.emailService = emailService;
this.paymentService = paymentService;
}
}

  • Depend on abstractions, not concrete implementations (DIP)
  • Use dependency injection for loose coupling
  • Minimize dependencies — each class should have few dependencies
  • Don’t create dependencies inside constructors — inject them

Previous Topic: Composition → Next Topic: Coupling vs Cohesion →