Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / SOLID Principles

    D: The Dependency Inversion Principle

    Dependency Inversion Principle (DIP): high-level code (business rules) should not depend on low-level code (email, databases); both

    Chapter 6 of 85 min readOften asked in interviews

    The Plain Picture#

    The lamp and the socket again. Your house's wiring doesn't depend on a particular lamp brand, and the lamp doesn't depend on your house's wiring. Both depend on a shared standard: the plug shape. Anyone can make a lamp that fits; any house with the standard socket accepts it.

    The Real Names#

    • Dependency Inversion Principle (DIP): high-level code (business rules) should not depend on low-level code (email, databases); both should depend on abstractions (interfaces).

    • A dependency is anything a class needs to do its job — a notifier, a repository, a clock.

    • Dependency Injection (DI) is the usual way to achieve DIP: instead of a class creating its dependencies with new, they're passed in — usually through the constructor (constructor injection).

    Under the Hood#

    The violation — the business rule is welded to one email library:

    Java
    class QuizService {
        private final EmailNotifier notifier = new EmailNotifier(
            "smtp.gmail.com",
            "hard-coded-password"
        ); // creates its own dependency
    
        void finish(String student, int points) {
            if (points >= 150) notifier.send(student, "Great job!");
        }
    }

    Switching to WhatsApp means editing QuizService. Testing it sends real emails.

    The fix — depend on an interface, inject the implementation:

    Java
    interface Notifier {
        void send(String to, String msg);
    } // the "plug standard"
    
    class EmailNotifier implements Notifier {
        public void send(String to, String msg) {
            System.out.println("EMAIL to " + to + ": " + msg);
        }
    }
    
    class FakeNotifier implements Notifier {
        // for tests: just records messages
        final List<String> sent = new ArrayList<>();
    
        public void send(String to, String msg) {
            sent.add(to + "|" + msg);
        }
    }
    
    class QuizService {
        private final Notifier notifier;
    
        QuizService(Notifier notifier) {
            this.notifier = notifier;
        } // INJECTED through the constructor
    
        void finish(String student, int points) {
            if (points >= 150) notifier.send(student, "Great job! " + points + " points");
        }
    }
    Java
    new QuizService(new EmailNotifier()).finish("priya@example.com", 180);
    
    // EMAIL to priya@example.com: Great job! 180 points
    
    FakeNotifier fake = new FakeNotifier();
    
    new QuizService(fake).finish("rahul@example.com", 120); // below 150 — no message
    
    new QuizService(fake).finish("aisha@example.com", 200);
    
    System.out.println(fake.sent);
    // [aisha@example.com|Great job! 200 points]

    The same QuizService code runs against real email in production and a fake in tests — and a test can now check the rule ("only scores ≥ 150 get a message") in milliseconds. WhatsApp support = one new class, WhatsAppNotifier implements Notifier.

    The "inversion":

      BEFORE:  QuizService ──depends on──▶ EmailNotifier            (business rules depend on details)
    
      AFTER:   QuizService ──depends on──▶ «Notifier» ◀──implements── EmailNotifier
                                                ▲
                                                └────implements────── FakeNotifier, WhatsAppNotifier
                                                                      (details depend on the abstraction)

    Who does the injecting? Somewhere at the start of the program ("the composition root"), code builds the objects and wires them together. In real apps a DI framework does it: Spring in Java, and FastAPI's Depends in Python (FastAPI Models and Dependency Injection (coming soon)). Same idea, automated.

    Gotchas

    • Don't inject everything. Simple values and stable library classes (String, ArrayList, Math) don't need interfaces. Inject things that do I/O (databases, network, email, files), things that vary (payment providers), and things that make tests hard (the current time, random numbers).

    • Constructor injection > field setters: the object is complete the moment it's built, dependencies can be final, and missing ones are obvious.

    Check yourself

    4 questions
    1

    State DIP.

    Show answer

    High-level modules shouldn't depend on low-level modules; both should depend on abstractions.

    2

    What is dependency injection, and what's the preferred form?

    Show answer

    Passing a class the objects it needs instead of it creating them; constructor injection.

    3

    How does DIP make QuizService testable?

    Show answer

    A test passes a FakeNotifier, so no real email is sent and the test can inspect what would have been sent.

    4

    Why is "the current time" a good thing to inject?

    Show answer

    Code that calls the real clock gives different results each run; injecting a clock lets tests fix the time (e.g. "exam week").