Coupling describes how a class depends on other classes to do its job. Loosely coupled code needs few details about a component to use it. Reducing coupling can make components easier to change and test without affecting unrelated code. section 8.2 section 13.4.4
Loosening an email dependency
A registration handler that creates an EmailSender must know how to construct it and its dependencies. Passing EmailSender as a parameter removes that construction work from the handler. If the sender gains another dependency, the handler no longer needs to change just to wire it up. section 8.1 section 8.2
Listing 8.3 Sending email without DI when you create dependencies manually
string RegisterUser(string username)
{
var emailSender = new EmailSender( #1
new MessageFactory(), #2
new NetworkClient( #3
new EmailServerSettings #4
( #4
Host: "smtp.server.com", #4
Port: 25 #4
)) #4
);
emailSender.SendEmail(username); #5
return $"Email sent to {username}!";
}
Manual construction makes the registration handler responsible for wiring up the email sender and its dependencies. section 8.1
The handler can go further by accepting an IEmailSender interface rather than the concrete EmailSender class. It then relies on the interface's SendEmail method, not a particular implementation. A test can supply a stub or mock instead of sending real email. section 8.2
Listing 8.5 Using interfaces with dependency injection
string RegisterUser(string username, IEmailSender emailSender) #1
{
emailSender.SendEmail(username); #2
return $"Email sent to {username}!";
}
The handler declares its email dependency as an interface and uses it without constructing an implementation. section 8.2
Dependency injection helps provide dependencies without making the consuming code construct them. It adds wiring, though, which may not be worthwhile in a simple application. section 8.1
Coupling also matters between larger parts of an application. Keeping HTML generation, business logic, and request handling separate gives each a clearer responsibility. For example, if HTML generation relies on business-class names, renaming a class can unexpectedly break the website. section 13.4.4 section 13.4.4
















