Skip to main content
OOP and design · Topic 12 of 12

Dependency inversion

Definition​

The dependency inversion principle says high-level code should depend on an abstraction, not on a concrete class. The concrete class is passed in from outside, which makes it easy to swap and to test.

Example code​

A service that gets its sender from outside

interface MessageSender {
void send(String to, String text);
}

class OrderService {
private final MessageSender sender; // depends on the interface only

OrderService(MessageSender sender) { this.sender = sender; }

void placeOrder(String customer) { sender.send(customer, "Your order is confirmed"); }
}

class FakeSender implements MessageSender { // in a test, pass a fake instead of a real sender
String lastMessage;
public void send(String to, String text) { lastMessage = to + ": " + text; }
}

class Demo {
public static void main(String[] args) {
FakeSender fake = new FakeSender();
new OrderService(fake).placeOrder("asha@example.com");
System.out.println(fake.lastMessage);
}
}

// Output:
// asha@example.com: Your order is confirmed

Finished this page? Track your progress (saved only in your browser).