Dependency Inversion: let the policy own the interface
Keep your business rules untouched when you swap how messages are sent.
Watch the narrated video
Every step
Problem
Steps 1–4Refactor
Steps 5–10Payoff
Steps 11–12C# bonus
Step 13Recap
Steps 14–15The code: before and after
Before
record Customer(string Name, string Email, string Phone);
record Order(int Id, Customer Customer, int Total);
record SmtpMailer(string Host)
{
public void SendMail(string to, string subject, string body) =>
Console.WriteLine($"mail to {to}: {subject}: {body}");
}
class ReceiptService
{
private readonly SmtpMailer _mailer;
public ReceiptService()
{
_mailer = new SmtpMailer("smtp.shop.test");
}
public void SendReceipt(Order order)
{
var text = $"Order {order.Id} paid: {order.Total} EUR";
_mailer.SendMail(order.Customer.Email, "Your receipt", text);
}
}
class Shop
{
public static void Main()
{
var ana = new Customer("Ana", "ana@shop.test", "0700 111 222");
var order = new Order(42, ana, 30);
new ReceiptService().SendReceipt(order);
}
}After
record Customer(string Name, string Email, string Phone);
record Order(int Id, Customer Customer, int Total);
record SmtpMailer(string Host)
{
public void SendMail(string to, string subject, string body) =>
Console.WriteLine($"mail to {to}: {subject}: {body}");
}
record SmsGateway(string ApiKey)
{
public void SendText(string phone, string text) =>
Console.WriteLine($"text to {phone}: {text}");
}
class EmailReceipts(SmtpMailer mailer) : IReceiptChannel
{
public void Send(Customer customer, string text) =>
mailer.SendMail(customer.Email, "Your receipt", text);
}
class SmsReceipts(SmsGateway gateway) : IReceiptChannel
{
public void Send(Customer customer, string text) =>
gateway.SendText(customer.Phone, text);
}
interface IReceiptChannel
{
void Send(Customer customer, string text);
}
class ReceiptService(IReceiptChannel channel)
{
public void SendReceipt(Order order)
{
var text = $"Order {order.Id} paid: {order.Total} EUR";
channel.Send(order.Customer, text);
}
}
class Shop
{
public static void Main()
{
var ana = new Customer("Ana", "ana@shop.test", "0700 111 222");
var order = new Order(42, ana, 30);
var gateway = new SmsGateway("demo-key");
new ReceiptService(new SmsReceipts(gateway)).SendReceipt(order);
}
}Transcript, step by step
Problem
Step 1: A shop that mails receipts Before
Ana's order 42 goes to Receipt Service, which mails the receipt through SMTP Mailer's Send Mail. Receipt Service creates that mailer itself in its constructor, builds the receipt text, and mails it to the customer. Receipts were always mailed, so calling the mailer straight from the receipt code was the shortest path.
Step 2: Receipts go by text Change request
Customers read texts faster than mail, so receipts now go to the customer's phone as a text message. The quick way adds SMS Gateway, built with an API key, and its Send Text method takes a phone and a text. Then Receipt Service changes its field type, builds the gateway in its constructor, and calls Send Text with the phone. It compiles, and the program now prints the receipt as a text to Ana's phone.
Step 3: The rule depends on a detail Code smell
Receipt Service holds the business rule, what a receipt says and when it goes out, and that code is called the policy. SMS Gateway does one technical job the rule doesn't care about, so it's called a detail. Yet the policy depends on that detail, because it names the gateway's type here, creates it here, and calls its method here. The receipt text line didn't change, but the policy was edited in three places for a change in delivery. And the policy can't run at all without building a real gateway with its API key.
Step 4: Dependency Inversion Principle
So the policy should declare an interface in its own words, and the gateway should depend on it. Right now the dependency points the other way, from the policy down to the gateway.
Refactor
Step 5: Refactor first Back it out
We take the gateway back out, so receipts go by mail again. Then we refactor in small steps, and text messages come back once the policy owns its interface.
Step 6: Delivery in its own method Extract Method
So delivery gets its own home first: the mailer call moves into a private method called Deliver. Send Receipt now builds the text and hands it to Deliver, so the output is the same mail line.
Step 7: Email receipts move out Extract Class
But Deliver still lives inside the policy, so it moves out into a new class, Email Receipts. Email Receipts gets the mailer through its constructor, and Deliver becomes its Send method. Receipt Service now creates an Email Receipts and calls Send, so it no longer calls the mailer's method.
Step 8: The policy names its need Extract Interface
Right next to Receipt Service we declare the Receipt Channel interface, with one method, Send, that takes a customer and a text. Email Receipts implements it, but nothing calls through the interface yet.
Step 9: Who owns the interface Extract Interface
You might put a mailer interface over SMTP Mailer instead, with Send Mail's address, subject and body. But a text has no subject, so the policy would still speak mail, and texts would edit it again. The Receipt Channel interface says what the policy needs, a customer and a text, and nothing about hosts or subjects. An interface declared by the code that calls it, in that code's words, is what Robert Martin calls interface ownership. But Receipt Service still names Email Receipts here, so it still depends on the mail detail.
Step 10: Pass the channel in Change Function Declaration
If Receipt Service still built Email Receipts itself, it would still name a mail type, and texts would edit it again. Its constructor now takes the channel and stores it, and passing it in like this is called constructor injection. The field type becomes the Receipt Channel interface too, so Receipt Service names no mail type at all. Shop builds the mailer, wraps it in Email Receipts, passes that in, and the same mail line prints. Before, the policy depended on the mailer, and now the detail depends on an interface the policy owns. That change in direction is the inversion the principle is named for.
Payoff
Step 11: Text messages, take two Payoff
How many lines of Receipt Service do you think have to change for text messages? SMS Gateway returns as it was, and SMS Receipts implements the Receipt Channel interface by sending the text to the customer's phone. Shop builds the gateway with its API key and passes an SMS Receipts in, so the receipt goes to Ana's phone.
Step 12: The policy did not change Payoff
Zero, because Receipt Service and the Receipt Channel interface didn't change to add text messages. The three places from before name only the Receipt Channel interface now, the field here, the constructor here, and the call here. Changing delivery meant adding SMS Receipts and editing Shop, because the policy owns the interface and the details plug into it. The policy declares the interface and each detail implements it, and that's called the Dependency Inversion Principle. But you pay with one more type to read, and Shop now has to put the pieces together itself.
C# bonus
Step 13: Primary constructor C# bonus
Before this step, Receipt Service spent a field and a whole constructor only to store the channel it was given. C sharp 12 primary constructors put that parameter on the class line, the way both receipt classes already take their sender. The parameter is in scope across the whole class, so Send Receipt calls the channel directly and the output stays the same. But unlike the read-only field it replaces, the parameter can be reassigned inside the class.
Recap
Step 14: Where we started, where we ended Before / after
On the left, Receipt Service created the SMTP Mailer itself and called Send Mail directly. So every change in delivery meant editing the policy. On the right, Receipt Service gets the channel through its constructor, an interface it declares in its own words. SMS Receipts plugs into that interface and keeps the gateway call to itself.
Step 15: When to reach for it Takeaways
Reach for it when a policy calls a detail that changes on its own schedule, like mail or payments. Skip it when the class you call is stable with no second version in sight, like the standard list types. Spot it by a business class that creates its own mail or database client, or an interface that copies a vendor's method. And dot net logging already works this way, because it declares the logger interface and each provider implements it.