These are the notes for Low-Level Design (LLD) episode 16: the D in SOLID, the Dependency Inversion Principle (DIP), and its partner, dependency injection (DI). A food order crashes because of a text message, a test refuses to run on a laptop, and from that pain we invent the fix: an abstraction owned by the client, constructor injection, a composition root, and finally a tiny IoC container, which is what frameworks like Spring do for you. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The real-life problem: the lamp wired into the wall
A hotel room lamp has its wires going straight into the wall. No plug, no socket.
- A guest wants a brighter lamp: you need an electrician to open the wall, for a lamp.
- You want to check the light switch: you can't until a real bulb is fitted. You can't test one part on its own.
Houses solved this long ago with a socket. The wall decides the shape of the socket, and any lamp that fits plugs in. Who decides the shape is the whole idea of this episode.
2. The problem in code: a policy that creates its own detail
A food-delivery app. SmsSender sends texts through an SMS gateway (the company's server that actually delivers text messages). On a laptop there is no gateway, so it throws. OrderService is the important class, and it creates its own SmsSender with new:
class SmsSender { // low-level detail
void send(String phone, String text) {
if (System.getenv("SMS_GATEWAY") == null)
throw new IllegalStateException("SMS gateway unreachable");
System.out.println("SMS to " + phone + ": " + text);
}
}
class OrderService { // high-level policy
private final SmsSender sms = new SmsSender(); // picks its own tool
void placeOrder(String phone, String item) {
System.out.println("Order placed: " + item);
sms.send(phone, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
new OrderService().placeOrder("98xxxxxx01", "masala dosa");
}
}
Order placed: masala dosa
Exception in thread "main" java.lang.IllegalStateException: SMS gateway unreachable
at SmsSender.send(Main.java:4)
at OrderService.placeOrder(Main.java:12)
at Main.main(Main.java:17)
Two problems, both caused by that one new:
- You can't run or test the order logic alone. It drags a real SMS gateway along.
- Switching to WhatsApp means editing
OrderService, the most important class, for a detail about messages.
3. High-level and low-level modules
- Module: a piece of code with one job: a class, or a group of classes (a package).
- High-level module: holds the policy, the business rules, the reason the app exists.
OrderService. - Low-level module: the how: sending a text, writing to a database, reading a file. Details you might swap.
SmsSender. - Dependency: A depends on B if A uses B, so a change in B can break A.
Here the dependency arrow points down: the important code depends on the replaceable code. That's backwards.
OrderService ───uses───▶ SmsSender (policy depends on detail: bad)
4. The Dependency Inversion Principle
Robert C. Martin wrote it down in 1996 in his "Engineering Notebook" column in The C++ Report:
A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions.
- Abstraction: here, an interface: the shape of a service, without the how. (Episode 7.)
- Detail: a concrete class that does the actual work.
Martin's own example was a tiny Copy program that read characters from a keyboard and wrote them to a printer, and couldn't write to a disk file without being changed. Same disease as our OrderService.
Who owns the interface?
The fix isn't just "add an interface". The interface is owned by the client (the code that uses it), named in the client's words, and shaped by what the client needs:
| Bad (owned by the detail) | Good (owned by the client) |
|---|---|
interface SmsApi { void sendSms(...); } |
interface Notifier { void notify(phone, text); } |
Lives next to SmsSender |
Lives next to OrderService |
| Changes when the SMS vendor changes | Changes only when the order logic needs something new |
Now SmsNotifier implements Notifier: the detail's arrow points up to the abstraction. That's the inversion.
OrderService ──uses──▶ «interface» Notifier ◁┄┄ SmsNotifier
◁┄┄ WhatsAppNotifier
5. Dependency injection: ask, don't create
Even with an interface, if OrderService still did new SmsNotifier() inside, nothing would change. So it doesn't create its dependency; it asks for it in its constructor.
Dependency injection (DI): handing an object the things it needs (its dependencies) from outside, instead of letting it create them. Through the constructor it's called constructor injection.
interface Notifier { // owned by OrderService: what IT needs
void notify(String phone, String text);
}
class SmsNotifier implements Notifier {
public void notify(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
}
class WhatsAppNotifier implements Notifier {
public void notify(String phone, String text) { System.out.println("WhatsApp to " + phone + ": " + text); }
}
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; } // constructor injection
void placeOrder(String phone, String item) {
System.out.println("Order placed: " + item);
notifier.notify(phone, "Your " + item + " is on the way");
}
}
public class Main { // composition root: the only place with "new"
public static void main(String[] args) {
new OrderService(new SmsNotifier()).placeOrder("98xxxxxx01", "masala dosa");
new OrderService(new WhatsAppNotifier()).placeOrder("98xxxxxx02", "filter coffee");
}
}
Order placed: masala dosa
SMS to 98xxxxxx01: Your masala dosa is on the way
Order placed: filter coffee
WhatsApp to 98xxxxxx02: Your filter coffee is on the way
Same OrderService, two notifiers, not one line of it changed.
The composition root
Composition root: the one place in the app where all objects are created and connected (usually main, or a framework's startup). Everywhere else, classes just ask for what they need. Real-life version: a restaurant manager decides who works in which kitchen, in one place; the chef doesn't hire his own staff.
6. Testing with a fake
Test double (or fake): a stand-in object used only in tests. This one sends nothing; it records messages in a list so the test can check them.
import java.util.*;
interface Notifier { void notify(String phone, String text); }
class FakeNotifier implements Notifier { // a test double: records, sends nothing
final List<String> sent = new ArrayList<>();
public void notify(String phone, String text) { sent.add(phone + " | " + text); }
}
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; }
void placeOrder(String phone, String item) {
notifier.notify(phone, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
FakeNotifier fake = new FakeNotifier();
new OrderService(fake).placeOrder("98xxxxxx01", "masala dosa");
System.out.println("messages sent: " + fake.sent.size());
System.out.println(fake.sent.get(0));
boolean ok = fake.sent.equals(List.of("98xxxxxx01 | Your masala dosa is on the way"));
System.out.println(ok ? "TEST PASSED" : "TEST FAILED");
}
}
messages sent: 1
98xxxxxx01 | Your masala dosa is on the way
TEST PASSED
No gateway, no network, no cost. The switch tested without a bulb. (Episode 53 does this properly with JUnit and Mockito.)
7. The half-fix: injecting a concrete class
Injection without an abstraction is still a wired-in lamp, just wired from outside:
class SmsNotifier {
void notify(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
}
class OrderService {
private final SmsNotifier notifier; // injected, but still a concrete class
OrderService(SmsNotifier notifier) { this.notifier = notifier; }
void placeOrder(String phone, String item) { notifier.notify(phone, "Your " + item + " is on the way"); }
}
class WhatsAppNotifier {
void notify(String phone, String text) { System.out.println("WhatsApp to " + phone + ": " + text); }
}
public class Main {
public static void main(String[] args) {
new OrderService(new WhatsAppNotifier()).placeOrder("98xxxxxx01", "masala dosa");
}
}
Main.java:14: error: incompatible types: WhatsAppNotifier cannot be converted to SmsNotifier
new OrderService(new WhatsAppNotifier()).placeOrder("98xxxxxx01", "masala dosa");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
You need both: inject it, and depend on the interface.
8. The three kinds of injection
Constructor injection (the default)
Dependencies are constructor parameters, stored in final fields. The object can't exist without them.
Setter injection
The object is created empty and a setter hands it the dependency later. Nothing forces the call:
interface Notifier { void notify(String phone, String text); }
class SmsNotifier implements Notifier {
public void notify(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
}
class OrderService {
private Notifier notifier; // no constructor parameter
void setNotifier(Notifier n) { this.notifier = n; } // setter injection
void placeOrder(String phone, String item) {
System.out.println("Order placed: " + item);
notifier.notify(phone, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
OrderService ok = new OrderService();
ok.setNotifier(new SmsNotifier());
ok.placeOrder("98xxxxxx01", "masala dosa");
OrderService forgot = new OrderService(); // someone forgot the setter
forgot.placeOrder("98xxxxxx02", "idli");
}
}
Order placed: masala dosa
SMS to 98xxxxxx01: Your masala dosa is on the way
Order placed: idli
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Notifier.notify(String, String)" because "this.notifier" is null
at OrderService.placeOrder(Main.java:10)
at Main.main(Main.java:20)
Interface injection
The class implements a small interface whose only method accepts the dependency; an injector (code that hands out dependencies) calls it:
interface Notifier { void notify(String phone, String text); }
interface NotifierAware { // the injector calls this
void injectNotifier(Notifier n);
}
class OrderService implements NotifierAware {
private Notifier notifier;
public void injectNotifier(Notifier n) { this.notifier = n; }
void placeOrder(String phone, String item) {
notifier.notify(phone, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
OrderService service = new OrderService();
Object[] parts = { service };
for (Object p : parts) // an injector
if (p instanceof NotifierAware a)
a.injectNotifier((ph, t) ->
System.out.println("Push to " + ph + ": " + t));
service.placeOrder("98xxxxxx01", "masala dosa");
}
}
Push to 98xxxxxx01: Your masala dosa is on the way
Which one?
| Kind | How | Use for | Risk |
|---|---|---|---|
| Constructor | OrderService(Notifier n) |
Required dependencies (most of them) | Long constructors signal too many responsibilities |
| Setter | setNotifier(n) |
Optional dependencies with a sensible default | Forgotten call: NullPointerException |
| Interface | implements NotifierAware |
Rare; some older frameworks | Extra interfaces, more ceremony |
The Spring reference documentation gives the same rule of thumb: constructors for mandatory dependencies, setters for optional ones, and says the Spring team "generally advocates constructor injection" because it allows immutable objects and guarantees required dependencies are not null.
9. Service locator: the alternative that hides dependencies
A service locator is a global registry: code asks it "give me a Notifier" and it looks one up.
import java.util.*;
interface Notifier { void notify(String phone, String text); }
class SmsNotifier implements Notifier {
public void notify(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
}
class ServiceLocator { // a global registry of services
private static final Map<Class<?>, Object> services = new HashMap<>();
static <T> void register(Class<T> type, T impl) { services.put(type, impl); }
static <T> T get(Class<T> type) {
Object s = services.get(type);
if (s == null) throw new IllegalStateException("No service registered for " + type.getSimpleName());
return type.cast(s);
}
}
class OrderService { // constructor says nothing about Notifier
void placeOrder(String phone, String item) {
ServiceLocator.get(Notifier.class).notify(phone, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
new OrderService().placeOrder("98xxxxxx01", "masala dosa");
}
}
Exception in thread "main" java.lang.IllegalStateException: No service registered for Notifier
at ServiceLocator.get(Main.java:12)
at OrderService.placeOrder(Main.java:18)
at Main.main(Main.java:23)
The constructor of OrderService says nothing about a Notifier; its signature (a method's name plus its parameter types) hides the dependency. Missing services show up only at run time, and every class now depends on the locator.
| Dependency injection | Service locator | |
|---|---|---|
| Direction | Pushed in from outside | Pulled out by the class |
| Visible in the constructor? | Yes | No |
| Missing dependency found | When the object is built (or at compile time) | Deep inside a call, at run time |
| Class depends on | Only the abstraction | The abstraction and the locator |
Martin Fowler compared the two in his January 2004 article Inversion of Control Containers and the Dependency Injection pattern and concluded that the choice matters less than "the principle of separating configuration from use". Today most teams prefer injection.
10. Inversion of control and IoC containers
- Inversion of control (IoC): normally your code creates every object it needs and calls them. With IoC, something else creates objects and calls your code. "Don't call us, we'll call you." You've seen it before: a stream calls your lambdas (episode 5).
- Dependency injection is IoC applied to one thing: creating dependencies. Fowler coined the name DI in that 2004 article because "Inversion of Control is too generic a term".
- IoC container: a library that creates objects and wires their dependencies for you.
A container in a few lines: a map from a type to a recipe (a function that knows how to build that type):
import java.util.*;
import java.util.function.*;
interface Notifier { void notify(String phone, String text); }
class SmsNotifier implements Notifier {
public void notify(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
}
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; }
void placeOrder(String phone, String item) { notifier.notify(phone, "Your " + item + " is on the way"); }
}
class Container { // a tiny IoC container
private final Map<Class<?>, Function<Container, ?>> recipes = new HashMap<>();
<T> void bind(Class<T> type, Function<Container, T> recipe) { recipes.put(type, recipe); }
<T> T get(Class<T> type) {
System.out.println(" container builds " + type.getSimpleName());
return type.cast(recipes.get(type).apply(this));
}
}
public class Main {
public static void main(String[] args) {
Container c = new Container();
c.bind(Notifier.class, k -> new SmsNotifier());
c.bind(OrderService.class, k -> new OrderService(k.get(Notifier.class)));
c.get(OrderService.class).placeOrder("98xxxxxx01", "masala dosa");
}
}
container builds OrderService
container builds Notifier
SMS to 98xxxxxx01: Your masala dosa is on the way
To switch the whole app to WhatsApp you would change one bind line.
Spring, in one paragraph (overview)
Spring is the most widely used Java framework, and at its core it is an IoC container. Its container is the ApplicationContext; the objects it creates and manages are called beans. You mark a class with an annotation such as @Component or @Service; Spring finds it, sees what its constructor needs, builds those first and plugs them in: exactly what our tiny container does, plus scopes, configuration, lifecycle and much more. (Spring is a separate library, so it isn't run in these notes.)
The class diagram
«composition root» Main ──creates──▶ OrderService ──uses──▶ «interface» Notifier
└─creates──▶ SmsNotifier ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄▷ Notifier
FakeNotifier ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄▷ Notifier
Dashed arrows with an open head are dependencies ("uses"); dashed lines with a hollow triangle are realizations ("implements"). Episode 18 covers the notation fully.
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
private final SmsSender sms = new SmsSender(); |
IllegalStateException: SMS gateway unreachable |
The policy creates its own detail | Ask for it in the constructor |
OrderService(SmsNotifier n) |
incompatible types: WhatsAppNotifier cannot be converted to SmsNotifier |
Injected a concrete class | Depend on Notifier |
| Required dependency via a setter | NullPointerException: Cannot invoke "Notifier.notify(String, String)" because "this.notifier" is null |
Nothing forces the call | Constructor injection |
ServiceLocator.get(Notifier.class) |
IllegalStateException: No service registered for Notifier |
Hidden dependency, found at run time | Inject it |
Interface named after the detail (SmsApi) |
no error: the abstraction leaks vendor details | The detail owns the abstraction | Name it for the client's need (Notifier) |
new calls scattered everywhere |
no error: hard to swap or test | No composition root | Create and connect objects in one place |
Mini project
Add two dependencies to OrderService: a Notifier and a Clock, so a test can fix the time. After 11 pm the kitchen is closed. Write an EmailNotifier without touching OrderService, and test both cases with a fake notifier (a lambda) and a FixedClock.
Solution
import java.time.*;
import java.util.*;
interface Clock { LocalTime now(); } // abstraction owned by the shop
interface Notifier { void notify(String phone, String text); }
class SystemClock implements Clock { public LocalTime now() { return LocalTime.now(); } }
class FixedClock implements Clock { // test double for time
private final LocalTime t;
FixedClock(LocalTime t) { this.t = t; }
public LocalTime now() { return t; }
}
class EmailNotifier implements Notifier {
public void notify(String to, String text) { System.out.println("Email to " + to + ": " + text); }
}
class OrderService {
private final Notifier notifier; private final Clock clock;
OrderService(Notifier notifier, Clock clock) { this.notifier = notifier; this.clock = clock; }
void placeOrder(String to, String item) {
if (clock.now().isAfter(LocalTime.of(23, 0))) { notifier.notify(to, "Sorry, kitchen closed"); return; }
notifier.notify(to, "Your " + item + " is on the way");
}
}
public class Main {
public static void main(String[] args) {
List<String> sent = new ArrayList<>();
Notifier fake = (to, text) -> sent.add(text);
new OrderService(fake, new FixedClock(LocalTime.of(23, 30))).placeOrder("asha@example.com", "dosa");
new OrderService(fake, new FixedClock(LocalTime.of(12, 0))).placeOrder("asha@example.com", "dosa");
System.out.println(sent);
new OrderService(new EmailNotifier(), new FixedClock(LocalTime.NOON)).placeOrder("asha@example.com", "idli");
}
}
Output:
[Sorry, kitchen closed, Your dosa is on the way]
Email to asha@example.com: Your idli is on the way
Time is a dependency too: injecting a Clock makes time-based rules testable (episode 53 returns to this).
Practice
1. Which of these follows the DIP? Explain each.
class ReportService {
// A: private final MySqlDb db = new MySqlDb();
// B: ReportService(MySqlDb db) { ... }
// C: ReportService(ReportStore store) { ... }
// D: ReportStore s = Locator.get(ReportStore.class);
}
Answer
C. ReportStore is an interface in the report service's own words, injected through the constructor. A creates its own detail, B injects a concrete database, D hides the dependency in a locator.
2. Implement option C with an in-memory store, and make the constructor reject null.
Solution
import java.util.*;
interface ReportStore { void save(String name, String body); List<String> names(); } // owned by ReportService
class InMemoryStore implements ReportStore {
private final Map<String, String> data = new LinkedHashMap<>();
public void save(String name, String body) { data.put(name, body); }
public List<String> names() { return new ArrayList<>(data.keySet()); }
}
class ReportService {
private final ReportStore store;
ReportService(ReportStore store) { this.store = Objects.requireNonNull(store, "store"); }
void monthly(String month, int sales) { store.save("sales-" + month, "Total: Rs " + sales); }
}
public class Main {
public static void main(String[] args) {
ReportStore store = new InMemoryStore();
ReportService reports = new ReportService(store);
reports.monthly("oct", 125000);
reports.monthly("nov", 98000);
System.out.println(store.names());
new ReportService(null);
}
}
[sales-oct, sales-nov]
Exception in thread "main" java.lang.NullPointerException: store
at java.base/java.util.Objects.requireNonNull(Objects.java:259)
at ReportService.<init>(Main.java:12)
at Main.main(Main.java:22)
Objects.requireNonNull makes a missing dependency fail immediately, at construction, with a clear message.
3. Is java.util.List an abstraction or a detail? Is ArrayList?
Answer
List is an abstraction (an interface); ArrayList is a detail (a concrete class). List<String> names = new ArrayList<>(); is a tiny DIP: the rest of the code depends on List, and only one line knows about ArrayList.
4. A class's constructor takes nine dependencies. What does that tell you?
Answer
It probably has too many responsibilities (an SRP smell, episode 12). DI didn't cause the problem; it made it visible. Split the class.
Quick quiz
void placeOrder(...) {
ServiceLocator.get(Notifier.class).notify(...);
}
What is the main problem?
- A. It's slower than
new - B. The dependency on
Notifieris hidden and fails only at run time - C. It doesn't compile
- D. It violates the Liskov Substitution Principle
Answer
B. The constructor doesn't reveal the dependency, and if nobody registered a Notifier, it fails deep inside a call: IllegalStateException: No service registered for Notifier.
Interview questions
- State the Dependency Inversion Principle. High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
- What is "inverted"? The direction of the source-code dependency: the detail now points up to an abstraction owned by the high-level module, instead of the policy pointing down to the detail.
- DIP vs dependency injection vs inversion of control? DIP is a design principle (depend on abstractions). DI is a technique (pass dependencies in from outside). IoC is the broader idea (a framework or container calls your code and creates your objects). DI is one form of IoC.
- Name the three kinds of injection. Which is preferred? Constructor, setter, interface. Constructor injection for required dependencies: the object is always complete, fields can be
final, and it's easy to test. - What is a composition root? The single place where the object graph is built and wired, usually
mainor the framework's startup. - Service locator vs DI? A locator is pulled by the class from a global registry; it hides dependencies and fails at run time. DI pushes dependencies in and makes them visible in the constructor.
- How does DI help testing? You can inject a test double (fake, stub, mock) instead of a real database, gateway or clock.
- What does Spring's
ApplicationContextdo? It is Spring's IoC container: it instantiates, configures and assembles beans, injecting their dependencies. - Does DIP mean every class needs an interface? No. Use abstractions at the boundaries that change or are hard to test (I/O, network, time, third-party APIs). Value objects and stable utilities don't need one.
- Who should own the interface? The client (the high-level module), named for what it needs, e.g.
Notifier, notSmsApi.
Glossary
| Term | Meaning, with an example |
|---|---|
| Dependency | A uses B, so a change in B can break A. OrderService depends on Notifier |
| Module | A piece of code with one job: a class or a package |
| High-level module | Holds the policy, the business rules. OrderService |
| Low-level module | Holds a detail: how to send, store or read. SmsNotifier |
| Policy | The business rule itself: "tell the customer when the order is placed" |
| Detail | A concrete way of doing something that might be swapped. SMS vs WhatsApp |
| Abstraction | An interface: the shape of a service without the how. Notifier |
| Dependency Inversion Principle (DIP) | Both high- and low-level modules depend on abstractions; details depend on abstractions |
| Abstraction owned by the client | The interface is named and shaped by the code that uses it |
| SMS gateway | A server that actually delivers text messages to phones |
| Dependency injection (DI) | Passing an object its dependencies from outside instead of letting it create them |
| Constructor injection | Dependencies passed as constructor parameters. new OrderService(notifier) |
| Setter injection | Dependencies passed later through a setter. setNotifier(n) |
| Interface injection | The class implements an interface whose method receives the dependency. NotifierAware |
| Injector | Code that hands dependencies to objects |
| Composition root | The one place where objects are created and connected, usually main |
| Test double / fake | A stand-in object used in tests. FakeNotifier records messages |
| Service locator | A global registry classes ask for services. ServiceLocator.get(Notifier.class) |
| Signature | A method's name plus its parameter types |
| Inversion of control (IoC) | Something else creates your objects and calls your code: "don't call us, we'll call you" |
| IoC container | A library that creates objects and wires their dependencies. Spring's ApplicationContext |
| Recipe | In our container, a function that knows how to build one type |
| Spring | A popular Java framework built around an IoC container |
ApplicationContext |
Spring's IoC container interface |
| Bean | An object created and managed by the Spring container |
| Annotation | Extra information attached with @, read by the compiler or tools. @Component |
Objects.requireNonNull |
Throws NullPointerException immediately if a value is null |
Summary
- DIP (Robert C. Martin, 1996): high-level policy and low-level details both depend on abstractions; the abstraction is owned by the client.
- Dependency injection: ask for dependencies, don't create them. Constructor injection for required ones; setters only for optional ones.
- Wire everything in one composition root; inject fakes in tests.
- A service locator hides dependencies until run time; prefer injection.
- IoC containers (like Spring's
ApplicationContext) automate the wiring.
Next episode: Beyond SOLID: DRY, KISS, YAGNI, the Law of Demeter and GRASP.