QA
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→

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

Why is Composition Over Inheritance a fundamental object-oriented design principle?