Beginner LevelSoftware Engineering Principles
Compare Dependency Injection (DI) versus the Service Locator pattern.
❓ Interview Prompt: Compare Constructor Dependency Injection vs Service Locator pattern, explicit vs implicit dependencies, and unit testability.
Comparing dependency management strategies:
•
Dependency Injection (DI): Dependencies are explicitly passed to a class via its constructor. Dependencies are transparent, and mocking in unit tests is effortless.
•
Service Locator (Anti-Pattern): Classes query a central registry ('ServiceLocator.get(Service)') to fetch dependencies internally. Hides class dependencies and creates tight coupling to the locator registry.
Code Implementation Example
typescript
// ❌ Service Locator: Hidden dependency
class InvoiceServiceBad {
private mailer = ServiceLocator.get(Mailer);
}
// ✅ Dependency Injection: Explicit constructor dependency
class InvoiceServiceGood {
constructor(private mailer: Mailer) {} // Clear & easily mockable!
}💡Contrasting implicit Service Locator lookup with explicit Dependency Injection.
🎯 Interview Key Takeaway
Prefer Constructor Dependency Injection over Service Locator to keep class dependencies explicit and easy to mock.
#Dependency Injection#Service Locator#Architecture#Beginner
Back to all Software Engineering Principles Questions→