LOW-LEVEL DESIGN · SOLID PRINCIPLES · D · 12 OF 48

Dependency Inversion Principle in Java: Depend on Abstractions

The D in SOLID, shown with a library late-book reminder that creates its own SQL table and SMS gateway. Learn high-level policy versus low-level detail, why the policy should own the interfaces it needs, what exactly gets inverted, wiring at a composition root, testing with fakes, and how dependency inversion differs from dependency injection and inversion of control.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 171 lines, with a small main() demo. Save it as DependencyInversionDemo.java, then run javac DependencyInversionDemo.java && java DependencyInversionDemo.

import java.time.Clock;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** Dependency inversion: a reminder rule welded to SQL and SMS, then depending only on abstractions. */
public class DependencyInversionDemo {

    public static void main(String[] args) {
        LocalDate march10 = LocalDate.of(2026, 3, 10);

        System.out.println("--- Before: the rule creates its own database and SMS objects ---");
        new OverdueReminderV1().run(march10);

        System.out.println();
        System.out.println("--- After: composition root wires real details ---");
        Clock clock = Clock.fixed(march10.atStartOfDay().toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
        LoanSource loans = new SqlLoanSource();
        MemberAlerts alerts = new SmsMemberAlerts(new SmsGateway("api-key-123"),
                Map.of("meera", "98100 00001"));
        new OverdueReminder(loans, alerts, clock).run();

        System.out.println();
        System.out.println("--- After: the same rule tested with fakes ---");
        RecordingAlerts sent = new RecordingAlerts();
        LoanSource oneLateLoan = new InMemoryLoanSource(
                List.of(new Loan("ravi", "Dune", LocalDate.of(2026, 1, 1))));
        new OverdueReminder(oneLateLoan, sent, clock).run();
        System.out.println("recorded: " + sent.messages());
        System.out.println("fine capped at 200: " + sent.messages().get(0).contains("200 rupees"));
    }
}

// Vendor code we do not own: a low-level detail.
class SmsGateway {
    private final String apiKey;

    SmsGateway(String apiKey) {
        this.apiKey = apiKey;
    }

    void sendSms(String phone, String text) {
        System.out.println("[sms via key " + apiKey.substring(0, 3) + "...] " + phone + ": " + text);
    }
}

// ---------------------------------------------------------------
// BEFORE: the business rule creates and depends on concrete details.
// ---------------------------------------------------------------
record LoanRow(String phone, String title, LocalDate due) { }

class SqlLoanTable {
    List<LoanRow> selectDue(LocalDate today) {
        System.out.println("[sql] SELECT phone, title, due FROM loans WHERE due < '" + today + "'");
        return List.of(new LoanRow("98100 00001", "The Hobbit", today.minusDays(12)));
    }
}

class OverdueReminderV1 {
    private final SqlLoanTable loans = new SqlLoanTable();             // hard-wired detail
    private final SmsGateway sms = new SmsGateway("api-key-123");     // hard-wired detail

    void run(LocalDate today) {
        for (LoanRow row : loans.selectDue(today)) {
            long days = ChronoUnit.DAYS.between(row.due(), today);
            long fine = Math.min(200, 5 * days);
            sms.sendSms(row.phone(), "Return " + row.title() + ", fine " + fine + " rupees");
        }
    }
}

// ---------------------------------------------------------------
// AFTER, high-level package: the policy and the interfaces it owns.
// ---------------------------------------------------------------
record Loan(String member, String title, LocalDate due) { }

interface LoanSource {
    List<Loan> overdueOn(LocalDate day);
}

interface MemberAlerts {
    void remind(String member, String message);
}

class OverdueReminder {
    private static final long FINE_PER_DAY = 5;
    private static final long MAX_FINE = 200;

    private final LoanSource loans;
    private final MemberAlerts alerts;
    private final Clock clock;

    OverdueReminder(LoanSource loans, MemberAlerts alerts, Clock clock) {
        this.loans = loans;
        this.alerts = alerts;
        this.clock = clock;
    }

    void run() {
        LocalDate today = LocalDate.now(clock);
        for (Loan loan : loans.overdueOn(today)) {
            long days = ChronoUnit.DAYS.between(loan.due(), today);
            long fine = Math.min(MAX_FINE, FINE_PER_DAY * days);
            alerts.remind(loan.member(), "Return " + loan.title() + ", " + days + " days late, fine " + fine
                    + " rupees");
        }
    }
}

// ---------------------------------------------------------------
// AFTER, low-level package: details implement the policy's interfaces.
// ---------------------------------------------------------------
class SqlLoanSource implements LoanSource {
    @Override
    public List<Loan> overdueOn(LocalDate day) {
        System.out.println("[sql] SELECT member, title, due FROM loans WHERE due < '" + day + "'");
        return List.of(new Loan("meera", "The Hobbit", day.minusDays(12)));
    }
}

/** An adapter: turns the vendor SMS API into the MemberAlerts shape the policy wants. */
class SmsMemberAlerts implements MemberAlerts {
    private final SmsGateway gateway;
    private final Map<String, String> phones;

    SmsMemberAlerts(SmsGateway gateway, Map<String, String> phones) {
        this.gateway = gateway;
        this.phones = Map.copyOf(phones);
    }

    @Override
    public void remind(String member, String message) {
        gateway.sendSms(phones.getOrDefault(member, "unknown"), message);
    }
}

// Test doubles: tiny, fast, deterministic.
class InMemoryLoanSource implements LoanSource {
    private final List<Loan> loans;

    InMemoryLoanSource(List<Loan> loans) {
        this.loans = List.copyOf(loans);
    }

    @Override
    public List<Loan> overdueOn(LocalDate day) {
        List<Loan> late = new ArrayList<>();
        for (Loan loan : loans) {
            if (loan.due().isBefore(day)) {
                late.add(loan);
            }
        }
        return late;
    }
}

class RecordingAlerts implements MemberAlerts {
    private final List<String> messages = new ArrayList<>();

    @Override
    public void remind(String member, String message) {
        messages.add(member + ": " + message);
    }

    List<String> messages() {
        return messages;
    }
}

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.

OverdueReminderV1
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.

What goes wrong
  • 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.

The principle
  • 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.

Two kinds of code
  • 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.

Ownership
  • 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.

OverdueReminder
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.

Low-level classes
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.

Composition root
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.

A fast test
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.

Not the same thing
  • 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.

Do not abstract everything
  • 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.

In Java and frameworks
  • 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.

How it relates
  • 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.

Where it comes up
  • 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

Interview questions

What is the dependency inversion principle?

High-level modules should not depend on low-level modules; both should depend on abstractions. And abstractions should not depend on details; details should depend on abstractions. Business rules talk to interfaces that infrastructure code implements.

What exactly is "inverted" in dependency inversion?

The direction of the source code dependency and the ownership of the interface. Instead of the business code importing the database class, the business package defines the interface it needs and the database code imports and implements it.

What is the difference between dependency inversion and dependency injection?

Dependency inversion is a design principle about which way dependencies point. Dependency injection is a technique for supplying an object with its dependencies from outside, for example through the constructor. You can inject a concrete class without following DIP, and follow DIP without any DI framework.

What is a composition root?

The single place near the program entry point where concrete classes are created and wired together, such as main or a framework configuration. Keeping all wiring there means the rest of the code only sees abstractions.

Should every class have an interface?

No. Abstract things that are external, slow or likely to change, such as databases, network services, vendors, time and randomness. Stable types like String, LocalDate or your own value objects are fine to use directly, and extra interfaces only add noise.

How does dependency inversion help testing?

Because the policy depends on interfaces, tests can pass simple in-memory fakes, recording stubs and a fixed clock. The rules run in milliseconds and give the same result every time, with no database or network.

Give an example of dependency inversion in the Java ecosystem.

JDBC: application code depends on the Connection, Statement and ResultSet interfaces in java.sql, and each database vendor supplies a driver that implements them. Swapping databases mostly means changing the driver and the URL, not the code that uses JDBC.

How would you apply DIP in a parking lot design?

Define interfaces such as PaymentGateway and TicketRepository in the core, named in domain terms. Card payments and database storage implement them, and the parking lot service receives them through its constructor, so it can be tested with in-memory fakes.