依存性注入(Dependency Injection, DI) は、オブジェクトが自身で依存関係を作成するのではなく、外部から依存関係を受け取る(注入される) パターンです。疎結合性、テスト可能性、柔軟性を促進する — 現代的なソフトウェアにおいて基本的で広く使用されているパターンです。
依存性注入とは
WITHOUT DI → a class CREATES its own dependencies (tightly coupled):
class OrderService { constructor() { this.db = new Database(); } } // hardcoded dependency
WITH DI → dependencies are PROVIDED (injected) from outside:
class OrderService { constructor(db) { this.db = db; } } // db is injected
→ the object doesn't create/control its dependencies → they're given to it
DIが重要である理由
✓ TESTABILITY → inject MOCKS/fakes in tests → test the class in isolation (the biggest win)
✓ LOOSE COUPLING → the class depends on an ABSTRACTION/interface, not a concrete class →
swap implementations easily
✓ FLEXIBILITY → change dependencies without changing the class (different configs, environments)
✓ EXPLICIT dependencies → constructor shows what the class needs (vs hidden creation)
✓ Separation of concerns → creation/wiring is separate from use
