Part 3 of 6 · 1 min read
Depending on a detail
Creating the concrete class inside.
Here is a booking service that sends a confirmation by email. It creates the sender itself.
class SmtpSender {
String send(String to, String msg) { return "SMTP to " + to + ": " + msg; }
}
class ServiceBefore {
private final SmtpSender sender = new SmtpSender();
String confirm(String user) { return sender.send(user, "Booked"); }
}
Calling confirm("asha") returns "SMTP to asha: Booked". It works, but three problems follow.
- To send text messages instead,
ServiceBeforeitself must be edited. That breaks OCP (module 2). - To test
confirm, a test would send a real email, or need a mail server. - The important rule, "confirm a booking", is tied to a detail, "how email is sent". The valuable code depends on the cheap code.
The word new is the clue. The line new SmtpSender() names a concrete class, and it creates a dependency on it. CA notes that in nearly every language, creating an object needs the name of its concrete class. This is why creation needs special care.
Check yourself:
1. What does confirm("asha") return?
2. Which line creates the dependency on the detail?
3. Name two problems this causes.