Part 4 of 6 · 2 min read
The inverted version
Receive an interface.
The fix has two steps. Write an interface that says what the service needs. Then let the service receive that interface from outside instead of creating it.
interface Notifier { String notify(String to, String msg); }
class SmtpNotifier implements Notifier {
public String notify(String to, String msg) { return "SMTP to " + to + ": " + msg; }
}
class SmsNotifier implements Notifier {
public String notify(String to, String msg) { return "SMS to " + to + ": " + msg; }
}
class BookingService {
private final Notifier notifier;
BookingService(Notifier notifier) { this.notifier = Objects.requireNonNull(notifier); }
String confirm(String user) { return notifier.notify(user, "Booked"); }
}
Now the caller decides which detail to use. With new BookingService(new SmtpNotifier()), the result is "SMTP to asha: Booked". With new SmsNotifier(), it is "SMS to asha: Booked". BookingService was not edited.
Tests become easy. A fake class records messages instead of sending them.
class FakeNotifier implements Notifier {
final List<String> log = new ArrayList<>();
public String notify(String to, String msg) { log.add(to + "|" + msg); return "fake"; }
}
After new BookingService(fake).confirm("asha"), the list fake.log holds one entry, asha|Booked. No email was sent.
The interface should be written from the service's point of view, in terms of what the service needs ("notify a person"), and not copied from one vendor's methods. Then any vendor can fit behind it.
Passing a dependency in through a constructor is called dependency injection. It is the simple way to apply DIP, and module 6 of Level 3 covers it fully.
Check yourself:
1. What are the two steps of the fix?
2. What does the test with FakeNotifier avoid?
3. From whose point of view should the interface be written?