🏗️Dependency Injection
Also known as DI, Inversion of Control, Constructor Injection
Code gets the parts it needs from outside. It does not make them itself.
Think of it like
Think of it like a chef handed their knives each morning. They do not forge their own.
Example
Lucy's OrderService needs an email sender. In the app she passes a real one. In tests she passes a fake that just records each email.
Why it matters
Code that makes its own database and email sender is hard to test. Code that is handed them is easy.
Definition
Example code
javascript
class OrderService {
constructor(mailer) { this.mailer = mailer; }
}
new OrderService(new SmtpMailer()); // the real app
new OrderService(new FakeMailer()); // a testCommon mistake
Key takeaways
- 1Handed, not made. Dependencies come in.
- 2Real or fake. The caller picks.
- 3Plain is fine. No framework needed.