Chapter 20 of 26

SOLID: Interface Segregation & Dependency Inversion

Think of the TV remote at home. Most people need only power, volume and channel buttons, but many remotes have fifty buttons. Now imagine that every time the manufacturer changed the "3D settings" button, everyone in India had to buy a new remote, even people who never pressed it. That is what happens in code when classes depend on interfaces that are bigger than they need.

This chapter covers the last two SOLID principles. The Interface Segregation Principle (ISP) is about keeping interfaces small and focused. The Dependency Inversion Principle (DIP) is about which direction dependencies should point. Together they finish the job started by SOLID: Single Responsibility & Open/Closed and SOLID: Liskov Substitution Principle.


Interface Segregation Principle (ISP)

Clients should not be forced to depend on methods they do not use.

Here "client" means any code that uses an interface: a class implementing it, or a method receiving it as a parameter. The principle says: instead of one large, general-purpose ("fat") interface, provide several small, role-specific interfaces.

Why Fat Interfaces Hurt

  • Implementers suffer: a class must write methods it cannot support, usually by throwing UnsupportedOperationException or leaving them empty. As we saw in the previous chapter, that is a recipe for LSP violations.

  • Users suffer: a method that takes the fat interface cannot tell from its type which operations will actually work.

  • Everyone is coupled to everything: a change to one method of the interface affects (and, in compiled languages, forces recompilation and redeployment of) every class that depends on the interface, even those that never use that method.

Example: An Office Machine Interface

// A "fat" interface: every device must implement every operation
interface Machine {
    void print(String doc);
    void scan(String doc);
    void fax(String doc, String number);
}

class AllInOnePrinter implements Machine {
    public void print(String doc) { System.out.println("Printing " + doc); }
    public void scan(String doc)  { System.out.println("Scanning " + doc); }
    public void fax(String doc, String number) {
        System.out.println("Faxing " + doc + " to " + number);
    }
}

// A cheap printer is FORCED to provide scan() and fax()
class BasicPrinter implements Machine {
    public void print(String doc) { System.out.println("Printing " + doc); }
    public void scan(String doc) {
        throw new UnsupportedOperationException("BasicPrinter cannot scan");
    }
    public void fax(String doc, String number) {
        throw new UnsupportedOperationException("BasicPrinter cannot fax");
    }
}

public class OfficeBad {
    static void scanAll(Machine m) {
        try {
            m.scan("aadhaar.pdf");
        } catch (UnsupportedOperationException e) {
            System.out.println("Runtime surprise: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        scanAll(new AllInOnePrinter());
        scanAll(new BasicPrinter());     // compiles fine, fails at run time
    }
}

Output:

Scanning aadhaar.pdf
Runtime surprise: BasicPrinter cannot scan

BasicPrinter is lying about what it can do. The compiler accepted scanAll(new BasicPrinter()) because the type said "I am a Machine, I can scan". The error appears only at run time, possibly in production.

Refactoring with ISP

Split the fat interface into role interfaces. A class implements only the roles it can really perform, and a multi-function device simply implements several of them.

// Small, role-based interfaces
interface Printer {
    void print(String doc);
}

interface Scanner {
    void scan(String doc);
}

interface FaxMachine {
    void fax(String doc, String number);
}

class BasicPrinter implements Printer {
    public void print(String doc) { System.out.println("Basic: printing " + doc); }
}

class AllInOnePrinter implements Printer, Scanner, FaxMachine {
    public void print(String doc) { System.out.println("AllInOne: printing " + doc); }
    public void scan(String doc)  { System.out.println("AllInOne: scanning " + doc); }
    public void fax(String doc, String number) {
        System.out.println("AllInOne: faxing " + doc + " to " + number);
    }
}

public class OfficeGood {
    // Each client asks only for the role it needs
    static void printReport(Printer p) { p.print("report.pdf"); }

    static void digitize(Scanner s)    { s.scan("aadhaar.pdf"); }

    public static void main(String[] args) {
        BasicPrinter basic = new BasicPrinter();
        AllInOnePrinter office = new AllInOnePrinter();

        printReport(basic);
        printReport(office);
        digitize(office);
        // digitize(basic);   // compile-time error: BasicPrinter is not a Scanner
    }
}

Output:

Basic: printing report.pdf
AllInOne: printing report.pdf
AllInOne: scanning aadhaar.pdf

If you remove the comment from the last line of main, the program no longer compiles:

OfficeGood.java:39: error: incompatible types: BasicPrinter cannot be converted to Scanner
        digitize(basic);   // compile-time error: BasicPrinter is not a Scanner
                 ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

The mistake that used to be a run-time exception is now caught by the compiler. That is the real benefit of ISP: types describe true capabilities.

 Before (fat)                         After (segregated)
 ┌──────────────────────┐             ┌─────────┐ ┌─────────┐ ┌────────────┐
 │       Machine        │             │ Printer │ │ Scanner │ │ FaxMachine │
 │ print() scan() fax() │             └────▲────┘ └────▲────┘ └─────▲──────┘
 └──────────▲───────────┘                  │           │            │
      ┌─────┴──────┐                 ┌─────┴───┐  ┌────┴────────────┴───┐
 AllInOne     BasicPrinter           │ Basic   │  │     AllInOne        │
              (2 fake methods)       │ Printer │  │ (implements all 3)  │
                                     └─────────┘  └─────────────────────┘

ISP in the Java Standard Library

The JDK uses many tiny interfaces that classes combine as needed: Comparable (one method), Runnable (one method), AutoCloseable (one method), Iterable, CharSequence and the functional interfaces in java.util.function. String, for example, implements Comparable, CharSequence and Serializable, and a method that only needs to compare things asks for a Comparable, not a String.

How Small Is Small Enough?

ISP does not mean "one method per interface". Group methods that clients always use together. A Stack interface with push, pop and peek is cohesive; splitting it would just create noise. Split when you find different groups of clients using different subsets of the methods, or implementers who cannot honestly support some methods.


Dependency Inversion Principle (DIP)

Robert Martin's statement has two parts:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.

  • High-level module: the important business policy, the code that says what the application does (place an order, calculate a salary).

  • Low-level module: a mechanism or detail, the code that says how something is done (talk to MySQL, send an email, write a file).

  • Abstraction: an interface or abstract class describing the service the high-level module needs.

Why "Inversion"?

In a naive, traditional design, dependencies follow the call direction: the business logic calls the database code, so it depends on the database code. Any change in the database layer can ripple up into the business logic.

 Traditional (no DIP)                    With DIP
 ─────────────────────                   ──────────────────────────────────
 ┌──────────────┐                        ┌──────────────┐    ┌─────────────────┐
 │ OrderService │                        │ OrderService │───▶│ «interface»     │
 └──────┬───────┘                        └──────────────┘    │ OrderRepository │
        │ depends on                       high-level         └────────▲────────┘
        ▼                                                              │ implements
 ┌──────────────┐                                            ┌─────────┴────────────┐
 │ MySqlDatabase│                                            │ MySqlOrderRepository │
 └──────────────┘                                            └──────────────────────┘
 policy depends on detail                low-level detail now depends UP on the abstraction

With DIP, the interface belongs to (is designed for) the high-level module. The low-level class depends on that interface by implementing it. The direction of the source-code dependency between the business layer and the database layer has been inverted, even though at run time the business code still calls the database code.

Example: An Order Service Without DIP

// Low-level details
class MySqlDatabase {
    void insert(String table, String row) {
        System.out.println("MySQL INSERT INTO " + table + " -> " + row);
    }
}

class GmailSender {
    void sendMail(String to, String body) {
        System.out.println("Gmail to " + to + ": " + body);
    }
}

// High-level policy that depends DIRECTLY on the details above
class OrderService {
    private final MySqlDatabase db = new MySqlDatabase();   // hard-wired
    private final GmailSender mail = new GmailSender();     // hard-wired

    void placeOrder(String customer, String item) {
        db.insert("orders", customer + "," + item);
        mail.sendMail(customer, "Your order for " + item + " is confirmed");
    }
}

public class ShopBad {
    public static void main(String[] args) {
        new OrderService().placeOrder("asha@example.com", "Laptop");
    }
}

Output:

MySQL INSERT INTO orders -> asha@example.com,Laptop
Gmail to asha@example.com: Your order for Laptop is confirmed

Problems with this design:

  • Rigid: switching from Gmail to SMS, or MySQL to PostgreSQL, means editing OrderService, the most important class in the system (an OCP violation too).

  • Hard to test: you cannot test placeOrder without a real database and real email, because the dependencies are created with new inside the class.

  • Not reusable: the business rules cannot be used in another setting (for example a different database) without dragging MySQL and Gmail along.

Refactoring with DIP

We define the abstractions the business logic needs, make OrderService depend only on them, and pass the concrete objects in through the constructor.

import java.util.ArrayList;
import java.util.List;

// ---- High-level module: business policy + the abstractions it needs ----
interface OrderRepository {
    void save(String customer, String item);
}

interface Notifier {
    void notify(String customer, String message);
}

class OrderService {
    private final OrderRepository repository;
    private final Notifier notifier;

    // Dependencies are injected: OrderService never uses 'new' on a detail
    OrderService(OrderRepository repository, Notifier notifier) {
        this.repository = repository;
        this.notifier = notifier;
    }

    void placeOrder(String customer, String item) {
        if (item.isBlank()) throw new IllegalArgumentException("empty item");
        repository.save(customer, item);
        notifier.notify(customer, "Your order for " + item + " is confirmed");
    }
}

// ---- Low-level modules: details that implement the abstractions ----
class MySqlOrderRepository implements OrderRepository {
    public void save(String customer, String item) {
        System.out.println("MySQL INSERT INTO orders -> " + customer + "," + item);
    }
}

class EmailNotifier implements Notifier {
    public void notify(String customer, String message) {
        System.out.println("Email to " + customer + ": " + message);
    }
}

class SmsNotifier implements Notifier {
    public void notify(String customer, String message) {
        System.out.println("SMS to " + customer + ": " + message);
    }
}

// ---- Test doubles: no database, no network ----
class InMemoryOrderRepository implements OrderRepository {
    final List<String> rows = new ArrayList<>();
    public void save(String customer, String item) { rows.add(customer + "," + item); }
}

class RecordingNotifier implements Notifier {
    final List<String> sent = new ArrayList<>();
    public void notify(String customer, String message) { sent.add(customer); }
}

public class ShopGood {
    public static void main(String[] args) {
        // Composition root: the ONE place that knows the concrete classes
        OrderService production = new OrderService(new MySqlOrderRepository(), new EmailNotifier());
        production.placeOrder("asha@example.com", "Laptop");

        OrderService smsShop = new OrderService(new MySqlOrderRepository(), new SmsNotifier());
        smsShop.placeOrder("+91-98xxxxxx10", "Headphones");

        // A quick "unit test" with fakes
        InMemoryOrderRepository repo = new InMemoryOrderRepository();
        RecordingNotifier notifier = new RecordingNotifier();
        new OrderService(repo, notifier).placeOrder("ravi@example.com", "Book");
        System.out.println("test rows = " + repo.rows + ", notified = " + notifier.sent);
    }
}

Output:

MySQL INSERT INTO orders -> asha@example.com,Laptop
Email to asha@example.com: Your order for Laptop is confirmed
MySQL INSERT INTO orders -> +91-98xxxxxx10,Headphones
SMS to +91-98xxxxxx10: Your order for Headphones is confirmed
test rows = [ravi@example.com,Book], notified = [ravi@example.com]

What we gained:

  • OrderService contains no mention of MySQL, email or SMS. Switching to SMS required a new class and a one-line change in main, not an edit to the business logic.

  • We tested the business logic with fakes (InMemoryOrderRepository, RecordingNotifier): fast, no database, no network.

  • All concrete classes are chosen in one place, often called the composition root (here, main).

Also notice how the interfaces are named: OrderRepository and Notifier describe what the business needs. They are not named MySqlInterface or EmailApi. That is part B of the principle: the abstraction must not be shaped by the details. If the interface had a method like executeSql(String query), it would leak MySQL into the high-level layer and the inversion would be fake.


DIP vs Dependency Injection vs IoC

These three terms are often confused in interviews:

Term

What it is

In our example

Dependency Inversion Principle

A design principle: depend on abstractions; abstractions are owned by high-level policy

OrderService depends on OrderRepository, not on MySqlOrderRepository

Dependency Injection (DI)

A technique: an object receives its dependencies from outside instead of creating them

Passing the repository and notifier into the constructor

Inversion of Control (IoC)

A broader idea: a framework or outside code controls object creation and the flow of calls, not your class

main (or a framework like Spring) builds and wires the objects

DI container

A tool that performs DI automatically from configuration or annotations

Spring, Jakarta CDI, Google Guice, Dagger

You can use DI without following DIP (injecting a concrete MySqlDatabase class still ties you to MySQL), and you can follow DIP without any framework, exactly as our main method did. DI is simply the most common way to supply the abstractions that DIP asks for.

Ways to Inject a Dependency

Style

How

Notes

Constructor injection

Pass dependencies to the constructor

Preferred: fields can be final, the object is never half-built, dependencies are obvious

Setter injection

Call setNotifier(...) after construction

Useful for optional dependencies; object may be used before it is fully set up

Method (parameter) injection

Pass the dependency to the method that needs it

Good when it varies per call (like the DiscountPolicy parameter in the OCP example)


A Quick Look at Python

Python does not need interfaces for polymorphism (duck typing), but the same principles apply. With typing.Protocol you can describe a small abstraction that any class with a matching method satisfies, even without inheriting from it:

from typing import Protocol


class Notifier(Protocol):          # an abstraction owned by the high-level code
    def notify(self, customer: str, message: str) -> None: ...


class SmsNotifier:                 # note: does NOT inherit from Notifier
    def notify(self, customer: str, message: str) -> None:
        print(f"SMS to {customer}: {message}")


class OrderService:
    def __init__(self, notifier: Notifier) -> None:
        self.notifier = notifier   # injected dependency

    def place_order(self, customer: str, item: str) -> None:
        self.notifier.notify(customer, f"Your order for {item} is confirmed")


OrderService(SmsNotifier()).place_order("Meera", "Pen drive")

Output:

SMS to Meera: Your order for Pen drive is confirmed

Notifier is a tiny, client-owned abstraction (ISP and DIP), and OrderService receives its dependency from outside (DI). A static type checker such as mypy verifies that SmsNotifier matches the protocol; at run time Python simply calls the method.


How ISP and DIP Fit with the Rest of SOLID

Principle

Focus

Main smell it fixes

SRP

Classes have one reason to change

God classes

OCP

Extend without modifying

if/else on type codes

LSP

Subtypes keep the parent's promises

"Not supported" overrides, instanceof checks

ISP

Interfaces are small and client-specific

Fat interfaces with dummy implementations

DIP

Policy depends on abstractions, not details

new of concrete infrastructure inside business classes

They reinforce each other. ISP gives you good, small abstractions; DIP makes the high-level code depend on them; OCP then lets you add new implementations freely; LSP makes sure those implementations behave; and SRP keeps each class focused enough to fit behind one abstraction. The overall result is the low coupling and high cohesion from the Coupling & Cohesion chapter.


Common Mistakes

  • Thinking ISP means one method per interface. Split by groups of clients, not by counting methods.

  • Implementing unsupported methods with empty bodies. Silent no-ops are even worse than exceptions, because nobody notices the bug.

  • Equating DIP with "use Spring". DIP is a design rule; frameworks are optional tools for wiring.

  • Creating interfaces that mirror the low-level API. An interface with executeSql() still makes the business layer depend on SQL. Design the abstraction from the high-level module's point of view.

  • Hiding new calls in every class "for convenience". Create concrete objects in one place (the composition root or a factory) and pass them in.

  • Abstracting stable things. You do not need an interface in front of String or ArrayList. Apply DIP to things that are volatile or slow to test: databases, networks, files, clocks, payment gateways.


Interview Questions

State the Interface Segregation Principle with an example.

Clients should not be forced to depend on methods they do not use. A Machine interface with print, scan and fax forces a basic printer to implement scan and fax; splitting it into Printer, Scanner and FaxMachine lets each class implement only what it supports.

How are ISP and LSP related?

Fat interfaces push implementers to write methods that throw UnsupportedOperationException or do nothing, which breaks the contract callers expect (an LSP violation). Segregating interfaces removes the need for such fake implementations.

State both parts of 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 exactly is "inverted" in DIP?

The direction of the source-code dependency. Traditionally policy code depends on detail code. With DIP, the policy code owns an abstraction and the detail code depends on (implements) it, so the dependency points from the low-level module up to the abstraction, opposite to the flow of control.

What is the difference between DIP and Dependency Injection?

DIP is a principle about what code should depend on (abstractions). Dependency Injection is a technique for supplying an object's dependencies from outside, for example through the constructor. DI is a common way to achieve DIP, but injecting concrete classes does not satisfy DIP.

Why is constructor injection usually preferred?

Dependencies are explicit and mandatory, the fields can be final (immutable), the object is fully initialized after construction, and it is easy to pass fakes in unit tests.


Summary

  • ISP: clients should not depend on methods they do not use. Prefer small role interfaces; a class can implement several.

  • Fat interfaces lead to fake implementations, run-time surprises and unnecessary coupling.

  • DIP: high-level policy and low-level details both depend on abstractions, and the abstractions are shaped by the policy, not by the details.

  • The source-code dependency is inverted relative to the flow of control.

  • Dependency Injection (preferably via constructor) supplies the implementations; concrete classes are chosen in one composition root.

  • Benefits: swappable implementations, easy unit testing with fakes, and business logic that is independent of frameworks and databases.

With SOLID complete, you now have the vocabulary to understand why well-known object-oriented solutions are shaped the way they are. In the next chapter, Introduction to Design Patterns, we start studying those reusable solutions.