Notes
The problem
A library sends reminders for late books. The overdue reminder class creates a SQL loan table and an SMS gateway with an API key, right in its fields. Its run method selects late loans from the table, works out a fine of five rupees per day, and sends an SMS. The rule itself, who is late and what they owe, is buried between database rows and vendor calls.
private final SqlLoanTable loans =
new SqlLoanTable();
private final SmsGateway sms =
new SmsGateway("api-key-123");
void run(LocalDate today) {
for (LoanRow r : loans.selectDue(today))
sms.sendSms(r.phone(), "Return " +
r.title() + ", fine " + fine(r));
} Why it hurts
Look at what this costs. To test the fine rule you need a real database and a real SMS account. If the library switches from SMS to email, you edit the business class. If the loans table gets a new column name, you edit the business class again. The rule cannot be reused anywhere else. Every arrow points from the important code toward the details, so the details control the rules.
- test the fine rule: needs a
- real database and SMS
- switch SMS to email: edit
- the business class
- schema change in loans table:
- edit the business class
- cannot reuse the rule in a
- nightly batch or an API
- arrows point: rules to details
The idea
The principle has two parts. First, high level modules should not depend on low level modules. Both should depend on abstractions. Second, abstractions should not depend on details. Details should depend on abstractions. In plain words, the business rule talks to an interface, and the database code and the SMS code implement that interface. Nobody points at the details anymore.
- 1. high-level modules should
- not depend on low-level
- modules; both should
- depend on abstractions
- 2. abstractions should not
- depend on details; details
- should depend on
- abstractions
High-level vs low-level
What do high level and low level mean here? High level policy is the business decision: a book is late after its due date, the fine is five rupees a day up to two hundred, and every late member gets a reminder. Low level detail is how that happens: the SQL query, the table names, the SMS vendor and its API key. Policy changes when the business changes. Details change when technology changes.
- high-level policy:
- late after due date
- five rupees a day, max 200
- remind every late member
- (changes when rules change)
- low-level detail:
- SQL queries, table names
- SMS vendor, API keys, HTTP
- (changes when tech changes)
The structure
Here is the new structure. The overdue reminder uses two interfaces: a loan source that finds overdue loans, and member alerts that sends a reminder. The SQL loan source implements the first, and SMS member alerts implements the second. Look at the arrows. The policy points at the interfaces, and the details also point at the interfaces. Nothing points from the policy to a detail.
What is inverted
So what exactly is inverted? Ownership. The interfaces live in the reminders package, next to the policy, and are named in the policy's language: loan source, member alerts, not SQL table or SMS API. The infrastructure package imports them and implements them. Before, the rules imported the database code. Now the database code imports the rules' interface. The source code dependency has flipped direction.
- package library.reminders
- OverdueReminder
- LoanSource (interface)
- MemberAlerts (interface)
- package library.infra
- SqlLoanSource
- SmsMemberAlerts
- infra imports reminders,
- never the other way
The policy in code
In code, loan source has one method, overdue on a given day, returning a list of loans. Member alerts has one method, remind a member with a message. The overdue reminder receives both through its constructor, along with a clock, because even the current date is a detail. Inside, it only holds the rule: five rupees per day late, capped at two hundred. No SQL, no HTTP, no vendor names.
interface LoanSource {
List<Loan> overdueOn(LocalDate day); }
interface MemberAlerts {
void remind(String member, String msg);}
OverdueReminder(LoanSource loans,
MemberAlerts alerts, Clock clock)
long fine(Loan l, LocalDate today):
min(200, 5 * daysLate) The details in code
The details are ordinary classes. The SQL loan source runs the query and turns rows into loan records. SMS member alerts looks up the member's phone number and calls the vendor's SMS gateway, which it wraps and hides. If the library moves to email or a different SMS vendor, you write a new class that implements member alerts. The overdue reminder does not change.
class SqlLoanSource
implements LoanSource {
public List<Loan> overdueOn(day) {
// SELECT ... WHERE due < ?
}
}
class SmsMemberAlerts
implements MemberAlerts {
// looks up the phone, then
// calls the vendor SmsGateway
} Wiring
Somebody still has to choose the real classes. That happens in one place at the edge of the program, often called the composition root. Here it is the main method. It creates the SQL loan source and the SMS alerts, and passes them into the overdue reminder. This is the only file that knows SQL and SMS are being used. In a framework, a container like Spring plays this role.
LoanSource loans = new SqlLoanSource();
MemberAlerts alerts =
new SmsMemberAlerts(gateway);
OverdueReminder reminder =
new OverdueReminder(loans, alerts,
Clock.systemDefaultZone());
reminder.run();
only this file names SQL and SMS Run-through
Run it on the tenth of March. The overdue reminder asks the loan source for overdue loans. Underneath, the SQL class runs its query. Meera's book is twelve days late, so the policy works out a fine of sixty rupees and asks member alerts to remind her. Underneath, the SMS class sends the text. The policy never knew a database or a phone was involved.
Testing
Testing is now easy. Pass an in memory loan source holding one very late loan, a recording alerts object that just remembers what it was asked to send, and a fixed clock. Run the reminder, then check that the fine was capped at two hundred and exactly one reminder was recorded. No database, no SMS account, no waiting, and the result is the same on every run.
var loans = new InMemoryLoanSource(
new Loan("ravi", "Dune",
date(2026, 1, 1)));
var sent = new RecordingAlerts();
new OverdueReminder(loans, sent,
fixedClock(2026, 3, 10)).run();
assert fine is capped at 200
assert one reminder recorded DIP vs DI vs IoC
Three names get mixed up. Dependency inversion is a design rule about which way dependencies point and who owns the abstraction. Dependency injection is a technique: you pass dependencies in, usually through the constructor, instead of creating them inside. An inversion of control container is a framework that does that wiring for you. You can inject a concrete class and still break inversion, and you can follow inversion with plain constructors and no framework.
- inversion (DIP): a design
- rule about which way source
- dependencies point
- injection (DI): a technique,
- passing dependencies in,
- e.g. through the constructor
- IoC container: a framework
- that does the wiring for you
- DI of a concrete class is not
- DIP; DIP needs no container
When not to
Do not put an interface in front of everything. Stable things like strings, dates, array lists and your own value records are fine to use directly. Abstract the things that are slow, external or likely to change: databases, network calls, third party vendors, the clock and random numbers. Creating an interface for every class by reflex just doubles the number of files without adding any flexibility.
- no interface needed for
- stable things: String,
- LocalDate, ArrayList,
- your own value records
- do abstract things that are
- slow, external or likely to
- change: DB, network, vendors,
- the clock, randomness
- one interface per class by
- reflex adds noise
Where you see it
Java uses this idea at scale. With JDBC, your code works with the connection and result set interfaces, and each database vendor ships a driver that implements them. The data source interface lets the connection pool be chosen at the edge. Java's clock class exists so time can be injected. And in Spring applications, services usually depend on repository interfaces, not on the classes that talk to the database.
- JDBC: your code uses
- Connection and ResultSet
- interfaces; each database
- driver implements them
- DataSource: the pool is
- chosen at the edge
- java.time.Clock: inject time
- Spring: services depend on
- repository interfaces
Related ideas
This principle ties the others together. It makes the open closed principle possible, because new details plug in without touching the policy. Interface segregation keeps the owned interfaces small. Our SMS alerts class is really an adapter, turning the vendor's API into the shape the policy wants. And the ports and adapters architecture is simply this principle applied to an entire application.
- open/closed: new details plug
- in without editing policy
- interface segregation: keep
- the owned interfaces small
- Adapter pattern: SmsMember
- Alerts adapts a vendor API
- ports and adapters: the whole
- app built this way
In LLD interviews
In LLD interviews, this is how you keep the core design clean. A parking lot takes payments through a payment gateway interface, not a card company's SDK. An expense splitting app saves through an expense repository interface, and you start with an in memory version. Two classic mistakes: creating a database class with new inside a service, and naming the interface after the vendor, which leaks the detail right back in.
- parking lot: PaymentGateway
- interface, not a card SDK
- splitwise: ExpenseRepository
- interface, in-memory first
- notifications: a Notifier
- port with many channels
- mistake: new MySqlRepo()
- inside a service
- mistake: interface named
- after the vendor