Skip to the page

OOP and SOLID · core

Dependency inversion and injection

High-level logic should depend on abstractions, not on concrete classes it creates itself. Pass dependencies in through the constructor so tests can use fakes.

The notes

What you must know

  • An OrderService that calls new MySqlOrderRepository and new SmsClient inside cannot be tested without a real database and SMS.
  • Define interfaces owned by the domain: OrderRepository and Notifier. MySqlOrderRepository and SmsNotifier implement them. Inject them: OrderService(OrderRepository repo, Notifier notifier).
  • Tests pass in-memory fakes or mocks. Dependency inversion is the principle. Dependency injection is one way to apply it. A container (Spring, NestJS) does the wiring, or you pass objects by hand.
  • Not every class needs an interface. Add one at boundaries (input and output, external services) or where there are real alternatives.
  • Other problems in such code: an API key hard-coded in source (use config or a secret store), SMS sent even if the save failed or before the commit, and no handling when SMS fails.
  • Making the dependencies static does not fix it. Mocking the new keyword is a workaround for a design problem.

The red pen

Common traps: mistake → fix

  • Mistake: Dependency inversion means using a DI framework

    Fix: the principle is about the direction of dependency; you can pass objects by hand.

  • Mistake: Every class needs an interface

    Fix: interfaces belong at boundaries and real alternatives.

  • Mistake: Static fields make it easy to test

    Fix: they hide global state and make tests share data.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the dependency inversion principle?
  2. How is it different from dependency injection?
  3. How would you make this service unit-testable?
  4. When is an interface not worth it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview