Design Patterns interview question · Most asked
What is the difference between dependency inversion, dependency injection and inversion of control?
Summary
Dependency inversion is a design principle (high-level code depends on abstractions it owns). Dependency injection is a technique for supplying dependencies from outside (usually through the constructor). Inversion of control is the broader idea that a framework or container calls your code and manages wiring, instead of your code controlling everything.
Longer Answer
- DIP (the D in SOLID):
OrderServicedepends on anOrderStoreinterface, not onMySqlOrderStore. - DI:
OrderService(store)receives its store; a composition root or container creates the real one. - IoC: "don't call us, we'll call you"; frameworks call your controllers, event handlers and lifecycle hooks. DI containers are one form of IoC.
You can apply DIP and DI with plain constructors and no framework at all.
Key Points
- DIP: principle about the direction of dependencies.
- DI: technique for passing dependencies in.
- IoC: framework controls the flow and wiring.
- DI doesn't require a container.
Deep dive: Design Patterns, Explained Simply: Dependency Injection Without a Framework
Explanation
What interviewers look for
Clear separation of principle, technique and broader concept.
Follow-up questions
- What is a composition root?
- Why is a service locator not the same as DI?
More most-asked Design Patterns questions
- How do you implement a Singleton, and why is it often considered an anti-pattern?
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- What problem does the Builder pattern solve? Show an example.
- What is the Adapter pattern? Give an example.