LLD

SOLID Principles

Dependency Inversion Principle

A clinic's booking rules should not depend on its SMS vendor or its database, and both sides should depend on an interface the booking code owns. We build an appointment service twice, once creating its SMS client and database connection itself and once taking two small interfaces, then switch SMS vendors and test the booking rule in each.

A clinic in Pune lets patients book a doctor online. When a booking goes through, the patient gets an SMS with the doctor's name and the time. Behind that message sit three kinds of code: the clinic's rule for booking a slot, a MySQL database that stores the bookings, and an SMS vendor's Java library.

The Dependency Inversion Principle says that the booking rule should not depend on the database or the vendor. The booking code should declare small interfaces for what it needs, and the database and SMS code should implement them.

The principle

The principle has two parts. High-level code, the rules the business cares about, should not depend on low-level code, the details of storage, messaging and networks. Both should depend on an abstraction, usually an interface. That interface describes what the high-level code needs, not how the low-level code happens to work.

The name comes from the direction of one arrow. In a first version that ignores the principle, the business class imports the vendor's class, so the arrow in the source code points from the rules down to the details. After the change, the business package declares an interface, and the vendor code imports that interface to implement it. That arrow now points up, from the details to the rules.

At run time nothing turns around. A booking still ends in a call to the vendor. What changes is which code has to know about the other.

What it does not say

  • It is not a framework. Passing objects into a constructor, and building them in one place such as main, is all the principle needs. A dependency injection framework does that wiring for you, which helps in a large app, but the design is the same without one.
  • It is not an interface for every class. String, List and LocalDateTime values are low-level, but they are stable and they do not reach outside the program, so code uses them directly. A record like Appointment is plain data and needs no interface either. The principle is for code that reaches outside the program or is likely to be swapped: a database, a vendor, the network, the system clock.
  • An interface that copies the vendor's methods is not inversion. We come back to this after the example.

Example: booking a clinic appointment

A booking has one rule: a doctor sees one patient per slot, so a second booking for a taken slot is refused. The first version creates what it needs itself:

package clinic.booking; import clinic.db.MySqlAppointmentRepository;import com.quicksms.QuickSmsClient; public class AppointmentService {    private static final Logger log = Logger.getLogger(AppointmentService.class.getName());    private final MySqlAppointmentRepository repository =            new MySqlAppointmentRepository("jdbc:mysql://db.clinic.local/bookings");    private final QuickSmsClient sms = new QuickSmsClient(System.getenv("QUICKSMS_KEY"));     public Appointment book(Patient patient, Doctor doctor, LocalDateTime slot) {        Appointment appointment = new Appointment(patient, doctor, slot);        if (!repository.insertIfFree(appointment)) {            throw new SlotTakenException(doctor, slot);        }        String text = "Your appointment with " + doctor.name() + " is at " + slot + ".";        QuickSmsClient.Response response = sms.dispatch("91" + patient.phone(), text, 60);        if (response.statusCode() != 202) {            log.warning("Confirmation not sent: QuickSMS status " + response.statusCode());        }        return appointment;    }}

insertIfFree relies on a unique key on the doctor and the slot, so two bookings that arrive together cannot both get it. QuickSMS wants the number as one run of digits with the country code, counts validity in minutes, and answers 202 when it accepts a message. These facts are about QuickSMS, and they sit in the class that holds the clinic's rule.

Two requests

Switch vendors. TextLane offers the clinic a lower price per message. TextLane's client wants "+91" and the number as two separate values, counts validity in seconds, and throws a checked TextLaneException instead of returning a status. Every one of those differences lands inside AppointmentService: the imports, the field, the dispatch line and the status check. The class that holds the slot rule is edited for a change that has nothing to do with slots.

Test the slot rule. A developer wants a test that books a slot twice and checks that the second booking is refused and that only one SMS goes out. The test must call new AppointmentService(), and that line builds the MySQL repository and a real QuickSMS client. So the test needs a running database, the first booking sends a real, paid SMS, and the test has no way to count the messages.

The rules sit on top of the details
AppointmentService holds the slot rule, the confirmation text, the QuickSMS details and the database setup. Below the dashed line, it creates and calls MySqlAppointmentRepository and the grey QuickSmsClient, the vendor's library. Both arrows point down, from the rules to the details. The two requests are in amber. Switching to TextLane edits the amber row, and the amber outline shows that this edit lands in the class that holds the slot rule. Testing the slot rule means building the whole class, and the red box says what that costs.AppointmentService holds the slot rule, the confirmation text, the QuickSMS details and the database setup. Below the dashed line, it creates and calls MySqlAppointmentRepository and the grey QuickSmsClient, the vendor's library. Both arrows point down, from the rules to the details. The two requests are in amber. Switching to TextLane edits the amber row, and the amber outline shows that this edit lands in the class that holds the slot rule. Testing the slot rule means building the whole class, and the red box says what that costs.
AppointmentService creates its database code and the vendor's client, so both requests land on it. AppointmentService holds the slot rule, the confirmation text, the QuickSMS details and the database setup. Below the dashed line, it creates and calls MySqlAppointmentRepository and the grey QuickSmsClient, the vendor's library. Both arrows point down, from the rules to the details. The two requests are in amber. Switching to TextLane edits the amber row, and the amber outline shows that this edit lands in the class that holds the slot rule. Testing the slot rule means building the whole class, and the red box says what that costs.

Following the principle

The booking code says what it needs, in its own words, as two interfaces in its own package:

package clinic.booking; /** What booking needs from storage. Returns false if the doctor already has that slot, even when two calls race. */public interface AppointmentStore {    boolean saveIfFree(Appointment appointment);} /** What booking needs from messaging: get this text to this patient. A failed send is logged, not thrown. */public interface PatientNotifier {    void send(Patient patient, String message);}

Neither interface mentions MySQL, QuickSMS, status codes or phone formats. The service takes both through its constructor and never creates either:

public class AppointmentService {    private final AppointmentStore store;    private final PatientNotifier notifier;     public AppointmentService(AppointmentStore store, PatientNotifier notifier) {        this.store = store;        this.notifier = notifier;    }     public Appointment book(Patient patient, Doctor doctor, LocalDateTime slot) {        Appointment appointment = new Appointment(patient, doctor, slot);        if (!store.saveIfFree(appointment)) {            throw new SlotTakenException(doctor, slot);        }        notifier.send(patient, "Your appointment with " + doctor.name() + " is at " + slot + ".");        return appointment;    }}

The vendor's details move into an adapter, a small class in another package that implements our interface by calling the vendor's client:

package clinic.sms; import clinic.booking.Patient;import clinic.booking.PatientNotifier;import com.quicksms.QuickSmsClient;import java.util.logging.Logger; public class QuickSmsNotifier implements PatientNotifier {    private static final Logger log = Logger.getLogger(QuickSmsNotifier.class.getName());    private final QuickSmsClient client;     public QuickSmsNotifier(QuickSmsClient client) {        this.client = client;    }     @Override    public void send(Patient patient, String message) {        QuickSmsClient.Response response = client.dispatch("91" + patient.phone(), message, 60);        if (response.statusCode() != 202) {            log.warning("QuickSMS refused the message: status " + response.statusCode());        }    }}

Look at the imports. The adapter imports clinic.booking.PatientNotifier, and nothing in clinic.booking imports clinic.sms. MySqlAppointmentStore does the same for the database: it implements AppointmentStore with the same insert and unique key.

One place, Main, builds the real objects and hands them to the service. This place is often called the composition root:

public class Main {    public static void main(String[] args) {        AppointmentStore store = new MySqlAppointmentStore(System.getenv("CLINIC_DB_URL"));        PatientNotifier notifier = new QuickSmsNotifier(new QuickSmsClient(System.getenv("QUICKSMS_KEY")));        AppointmentService service = new AppointmentService(store, notifier);         service.book(new Patient("Asha", "9876543210"), new Doctor("D7", "Dr Mehta"),                LocalDateTime.of(2026, 11, 24, 10, 30));    }}
The arrows now point up
The booking package imports no adapter and no vendor code. The dashed box at the top is the clinic.booking package. It holds AppointmentService and the two purple interfaces it uses, AppointmentStore and PatientNotifier. The adapters, MySqlAppointmentStore and QuickSmsNotifier, sit in their own packages below. Their implements arrows cross into clinic.booking going up. Each adapter uses the grey outside code below it: the MySQL JDBC driver and the vendor's QuickSmsClient.The booking package imports no adapter and no vendor code. The dashed box at the top is the clinic.booking package. It holds AppointmentService and the two purple interfaces it uses, AppointmentStore and PatientNotifier. The adapters, MySqlAppointmentStore and QuickSmsNotifier, sit in their own packages below. Their implements arrows cross into clinic.booking going up. Each adapter uses the grey outside code below it: the MySQL JDBC driver and the vendor's QuickSmsClient.
The booking package owns the interfaces. The adapters live outside it and implement them. The booking package imports no adapter and no vendor code. The dashed box at the top is the clinic.booking package. It holds AppointmentService and the two purple interfaces it uses, AppointmentStore and PatientNotifier. The adapters, MySqlAppointmentStore and QuickSmsNotifier, sit in their own packages below. Their implements arrows cross into clinic.booking going up. Each adapter uses the grey outside code below it: the MySQL JDBC driver and the vendor's QuickSmsClient.

The two requests again

Switch vendors. The switch is a new class, TextLaneNotifier, which implements PatientNotifier with TextLane's "+91" and its seconds, and catches TextLane's checked exception and logs it. In Main, the notifier line builds a TextLaneNotifier instead, and the imports change with it. AppointmentService and both interfaces stay as they are.

Test the slot rule. Each interface has one method, so a lambda can stand in for it. The test keeps taken slots in a Set and sent messages in a List:

class AppointmentServiceTest {    private final Set<String> takenSlots = new HashSet<>();    private final List<String> sentMessages = new ArrayList<>();    private final AppointmentService service = new AppointmentService(            appointment -> takenSlots.add(appointment.doctor().id() + "@" + appointment.slot()),            (patient, message) -> sentMessages.add(patient.phone() + ": " + message));     @Test    void refusesATakenSlotAndSendsNoMessage() {        Doctor mehta = new Doctor("D7", "Dr Mehta");        LocalDateTime slot = LocalDateTime.of(2026, 11, 24, 10, 30);        service.book(new Patient("Asha", "9876543210"), mehta, slot);         assertThrows(SlotTakenException.class,                () -> service.book(new Patient("Ravi", "9123456780"), mehta, slot));        assertEquals(1, sentMessages.size());    }}

The test needs no database and no SMS account, and it can count the messages because it holds the list.

One service, three wirings
Changing what fills the two interfaces never edits AppointmentService. Each column fills the two interfaces, named in purple, differently. In production, Main passes MySqlAppointmentStore and QuickSmsNotifier. After the switch, the amber TextLaneNotifier is the new class, and Main builds it in place of QuickSmsNotifier. In a test, two lambdas over a Set and a List fill both interfaces, so no database or SMS is involved. AppointmentService is the same class in all three.Changing what fills the two interfaces never edits AppointmentService. Each column fills the two interfaces, named in purple, differently. In production, Main passes MySqlAppointmentStore and QuickSmsNotifier. After the switch, the amber TextLaneNotifier is the new class, and Main builds it in place of QuickSmsNotifier. In a test, two lambdas over a Set and a List fill both interfaces, so no database or SMS is involved. AppointmentService is the same class in all three.
The same AppointmentService runs in production, after the vendor switch and in a test. Changing what fills the two interfaces never edits AppointmentService. Each column fills the two interfaces, named in purple, differently. In production, Main passes MySqlAppointmentStore and QuickSmsNotifier. After the switch, the amber TextLaneNotifier is the new class, and Main builds it in place of QuickSmsNotifier. In a test, two lambdas over a Set and a List fill both interfaces, so no database or SMS is involved. AppointmentService is the same class in all three.

An interface that copies the vendor

An interface in front of the vendor is not enough on its own. Suppose the team writes this one instead of PatientNotifier:

package clinic.booking; import com.quicksms.QuickSmsClient; // Shaped like QuickSMS, so the booking code still imports the vendor.public interface SmsGateway {    QuickSmsClient.Response dispatch(String msisdn, String body, int ttlMinutes);}

Its method is QuickSMS's method, and QuickSmsClient.Response is QuickSMS's own class, so the booking package still imports the vendor. When the clinic moves to TextLane, one of two things happens. Either this interface changes, along with every caller that builds a digits-only number and checks for 202. Or a TextLane adapter fakes QuickSMS responses, and the booking code keeps importing a vendor it no longer uses. The arrow still points from the rules to the vendor. Inversion needs the interface to be written from the business side, in the business's words, the way PatientNotifier.send(patient, message) is. The Interface Segregation Principle makes a related point: an interface should be shaped by the code that calls it.

When not to

An interface earns its place where the code meets something outside the program or something likely to be swapped. Inside the business logic, one class can use another directly. Suppose AppointmentService used a SlotFormatter that turns a time into "10:30 on 24 November". An interface for it would add a file and a step for every reader, and no vendor change or test would need it. A small script that runs once against one database does not need a store interface either. If a second vendor or a test appears later, adding the interface then is an edit to one class and the place that builds it.

In an interview

In a low-level design (LLD) round, draw every outside system, such as payments, SMS, a bank or a clock, as an interface the core owns, and pass it in through the constructor. Then say what that buys: a fake in tests, and a vendor switch that does not touch the rules. The Parking Lot takes its PaymentProcessor interface and a java.time.Clock through its constructor, and the ATM does the same with its Bank and Dispenser, which is what lets both run against fakes.

Common mistakes:

  • An interface shaped like the vendor. SmsGateway.dispatch(msisdn, body, ttlMinutes) keeps the vendor's types in the business package.
  • Creating the dependency inside the class. A PatientNotifier field set with new QuickSmsNotifier(...) in the constructor still ties the service to QuickSMS. Pass it in.
  • An interface for every class. Records, value objects and stable helpers can be used directly.
  • Treating the framework as the principle. A framework can wire the objects, but which interfaces exist and which package owns them are still your design choices.

Summary

  • High-level rules should not depend on low-level details. Both should depend on an interface.
  • The business code owns that interface and names it for its own need, like PatientNotifier.
  • The adapter imports the interface, so the source-code arrow points from the details to the rules. The call at run time still goes from the rules to the details.
  • One place, such as main, builds the real objects and passes them in through constructors. No framework is needed.
  • Put interfaces where the code meets something outside the program, such as a database, a vendor or a clock. Plain data and stable classes do not need one.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.