What is dependency injection, and why does it matter more than it sounds like?
Dependency injection is the way of giving a class the things it needs from outside, instead of the class making them for itself.
// Without injection. The class decides for itself.
public class OrderService {
public void place(Order order) {
SmtpEmailSender sender = new SmtpEmailSender();
sender.send(order.email(), "Your order is placed");
}
}
// With injection. The caller decides.
public class OrderService {
private final EmailSender sender;
public OrderService(EmailSender sender) {
this.sender = sender;
}
public void place(Order order) {
sender.send(order.email(), "Your order is placed");
}
}
And why does it matter more than it sounds like? Four reasons.
the reason what it buys
---------------------------------- --------------------------------------------
the class can be tested a fake instead of a real
server
the implementation can be changed a new sender is a new
argument
the class does not know about the the dependency is named in the
details constructor and nowhere else
the class is easier to read you can see what it needs
And the first one is the big one. Without injection, a test of the order service needs a real mail server or at least a stub of the network, and the test is slow and flaky. With injection you give it a fake that records what it was asked to send, and the test is three lines and runs instantly.
public class FakeEmailSender implements EmailSender {
private final java.util.List<String> sent = new java.util.ArrayList<>();
@Override
public void send(String to, String message) {
sent.add(to + ": " + message);
}
}
And there is one more reason that is worth knowing about, and it is about the design. When the class makes its own dependency then it has a hidden requirement. The reader of the class cannot see that it needs a mail server, because there is no field and no constructor parameter. So the requirement is a surprise.
the style the requirement
---------------------------- --------------------------------
made inside the class hidden, you find it when it fails
passed in the constructor written down, you can see it
And the last thing to say is that the name of the pattern is about the dependency being injected into the object, and not about the object injecting anything. The object is the one being given things.
So the rule to remember is this. Give the class its collaborators from outside so that the requirements are written down.
The last question in this topic is about the three kinds of injection.