Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
What is the primary practical benefit of using dependency injection in a class, compared to that class constructing its own dependencies internally?
💻 Code Challenge | +75 XP
Refactor an OrderService class that internally constructs a PostgresOrderRepository and a SendgridEmailService to instead accept both as constructor parameters, then write a test injecting fake versions of each.
A class is impossible to unit test because it directly instantiates a real database repository inside its constructor. Reorder the steps to fix it using dependency injection.
Task: Reorder the blocks in logical sequence to solve the problem.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
Constructing a class's dependencies internally within its own constructor
// Wrong: hardcoded, impossible to substitute for tests
class OrderService {
constructor() { this.repo = new PostgresOrderRepository(); }
}
// Correct: supplied from outside, swappable
class OrderService {
constructor(repo) { this.repo = repo; }
}The Solution //
This hardcodes the dependency permanently, making it impossible to substitute a test fake or an alternate implementation without modifying the class's own source code. Accept the dependency as a constructor parameter instead, letting the caller decide which implementation to supply.
The Error //
Using property injection (assigning a dependency after construction) instead of constructor injection
// Risky: object can be used before dependency is set
const service = new OrderService();
service.doSomething(); // BUG: repo is still undefined here!
service.repo = realRepo;
// Correct: guaranteed complete from the moment of construction
const service = new OrderService(realRepo);The Solution //
An object using property injection can exist in an incomplete, invalid state — instantiated but with a required dependency not yet assigned — if a developer forgets the assignment step or calls a method before it happens. Constructor injection guarantees the object can never exist without its required dependencies already in place.