Tight coupling and the new keyword
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite now wants to send an SMS instead of an email to customers in small towns. If OrderService creates its own EmailNotifier, that small change means opening the class that holds the order rules.
Tight coupling: a class that creates its own helper
Tight coupling means one class is fixed to one exact other class, usually by a new inside it, so it cannot work with anything else.
Example 1 is an OrderService that builds its own EmailNotifier inside placeOrder. It works, and for a 50-line program it is fine.
Example 1 · OrderService creates its own EmailNotifier
import java.math.BigDecimal;
class EmailNotifier { void send(String to, String message) { System.out.println(" EMAIL to " + to + ": " + message); }}
class OrderService { void placeOrder(int orderId, String customerEmail, BigDecimal amount) { System.out.println("Order " + orderId + " saved, amount Rs " + amount); EmailNotifier notifier = new EmailNotifier(); // OrderService makes its own helper notifier.send(customerEmail, "Your order " + orderId + " is confirmed"); }}
public class TightCouplingDemo { public static void main(String[] args) { OrderService service = new OrderService(); service.placeOrder(101, "asha@example.com", new BigDecimal("1499.00")); service.placeOrder(102, "ravi@example.com", new BigDecimal("349.50")); }}Order 101 saved, amount Rs 1499.00 EMAIL to asha@example.com: Your order 101 is confirmed Order 102 saved, amount Rs 349.50 EMAIL to ravi@example.com: Your order 102 is confirmed
What this code does
placeOrderbuilds a newEmailNotifieron every call.OrderServicehas no way to use anything else.mainonly createsOrderService; it never sees or chooses the notifier. That choice is hidden inside the method.
The hidden decision is the problem: OrderService decides how customers are told about orders, and nobody outside can change that decision without editing it.
Look for this shape in any code you read: a class with business rules (saving an order, checking an amount) that also builds its own helpers (a notifier, a database connection, a payment gateway).
Why new inside a class hurts: changing and testing
A dependency is an object that another object needs to do its job, such as the notifier an OrderService uses to confirm an order.
Example 2 runs three tests of placeOrder. Each test only wants to check the amount rule, yet each one also uses the notifier.
Example 2 · Testing placeOrder sends real emails
import java.math.BigDecimal;
class EmailNotifier { static int emailsSent = 0; // counts every email that really goes out
void send(String to, String message) { emailsSent++; System.out.println(" (real email sent to " + to + ")"); }}
class OrderService { void placeOrder(int orderId, String customerEmail, BigDecimal amount) { if (amount.signum() <= 0) { throw new IllegalArgumentException("Amount must be positive"); } EmailNotifier notifier = new EmailNotifier(); notifier.send(customerEmail, "Your order " + orderId + " is confirmed"); }}
public class TestingPainDemo { public static void main(String[] args) { OrderService service = new OrderService();
System.out.println("Test 1: a normal order"); service.placeOrder(1, "test1@example.com", new BigDecimal("499.00"));
System.out.println("Test 2: a small order"); service.placeOrder(2, "test2@example.com", new BigDecimal("1.00"));
System.out.println("Test 3: a zero amount must fail"); try { service.placeOrder(3, "test3@example.com", BigDecimal.ZERO); } catch (IllegalArgumentException e) { System.out.println(" failed as expected: " + e.getMessage()); }
System.out.println("Real emails sent while testing: " + EmailNotifier.emailsSent); }}Test 1: a normal order (real email sent to test1@example.com) Test 2: a small order (real email sent to test2@example.com) Test 3: a zero amount must fail failed as expected: Amount must be positive Real emails sent while testing: 2
What this code does
- The static counter stands in for a real mail server. Each
(real email sent ...)line would be a real email to a real inbox. - The tests only wanted to check the amount rule. They cannot stop the emails, because the
new EmailNotifier()is insideplaceOrder.
Two everyday requests show the pain. When the business says "small-town customers prefer SMS", you must edit OrderService, which holds the order rules, just to change how a message is delivered, and every edit to a class with rules risks breaking them.
Tests are worse. A test is code that runs a method with known inputs and checks the result. With new EmailNotifier() inside the method, every test sends a real email, fails when the mail server is down, and runs slowly while it waits for the network.
An interface alone does not fix it
Coding to an interface means a field or variable has an interface type, such as Notifier, instead of a class type, such as EmailNotifier.
Example 3 types the field as the interface Notifier. Watch which class still gets created, and where.
Example 3 · An interface field that still says new EmailNotifier()
import java.math.BigDecimal;
interface Notifier { void send(String to, String message);}
class EmailNotifier implements Notifier { public void send(String to, String message) { System.out.println(" EMAIL to " + to + ": " + message); }}
class SmsNotifier implements Notifier { public void send(String to, String message) { System.out.println(" SMS to " + to + ": " + message); }}
class OrderService { // The field type is the interface, but the choice is still made right here private final Notifier notifier = new EmailNotifier();
void placeOrder(int orderId, String contact, BigDecimal amount) { System.out.println("Order " + orderId + " saved, amount Rs " + amount); notifier.send(contact, "Your order " + orderId + " is confirmed"); }}
public class InterfaceStillCoupledDemo { public static void main(String[] args) { OrderService service = new OrderService(); service.placeOrder(103, "98450 12345", new BigDecimal("799.00")); System.out.println("SmsNotifier exists, but OrderService never uses it."); }}Order 103 saved, amount Rs 799.00 EMAIL to 98450 12345: Your order 103 is confirmed SmsNotifier exists, but OrderService never uses it.
What this code does
- The field type is
Notifier, but the field is set tonew EmailNotifier()insideOrderService, so a phone number gets an email. SmsNotifieris written and ready, yet unusable without editingOrderService. The interface alone changed nothing for the caller.
The field type is the interface, but the new still sits inside OrderService. The class still picks email, so switching to SMS still means editing it, and tests still send email.
The rule to remember: an interface makes swapping possible; moving the new out of the class makes swapping happen.
Find the bug
Find the line that still decides
Tap the line where the class still chooses its helper.
OrderService should work with any Notifier. Which line still decides?
Round 1 of 2The fix: pass the dependency in through the constructor
Constructor injection means a class receives its dependencies as constructor parameters and stores them in final fields, instead of creating them.
Example 4 gives OrderService a constructor that takes the Notifier, then uses the same class with email, SMS and a fake. Example 5 shows what happens to old callers.
Example 4 · Constructor injection: email, SMS and a fake for tests
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Objects;
interface Notifier { void send(String to, String message);}
class EmailNotifier implements Notifier { public void send(String to, String message) { System.out.println(" EMAIL to " + to + ": " + message); }}
class SmsNotifier implements Notifier { public void send(String to, String message) { System.out.println(" SMS to " + to + ": " + message); }}
class FakeNotifier implements Notifier { final List<String> sent = new ArrayList<>(); // remembers messages instead of sending them
public void send(String to, String message) { sent.add(to + " -> " + message); }}
class OrderService { private final Notifier notifier;
OrderService(Notifier notifier) { // the dependency comes in from outside this.notifier = Objects.requireNonNull(notifier, "notifier must not be null"); }
void placeOrder(int orderId, String contact, BigDecimal amount) { System.out.println("Order " + orderId + " saved, amount Rs " + amount); notifier.send(contact, "Your order " + orderId + " is confirmed"); }}
public class ConstructorInjectionDemo { public static void main(String[] args) { OrderService byEmail = new OrderService(new EmailNotifier()); byEmail.placeOrder(104, "asha@example.com", new BigDecimal("1499.00"));
OrderService bySms = new OrderService(new SmsNotifier()); bySms.placeOrder(105, "98450 12345", new BigDecimal("349.50"));
FakeNotifier fake = new FakeNotifier(); OrderService underTest = new OrderService(fake); underTest.placeOrder(106, "test@example.com", new BigDecimal("10.00")); System.out.println("Test check: messages recorded = " + fake.sent.size()); System.out.println("Test check: " + fake.sent.get(0)); }}Order 104 saved, amount Rs 1499.00 EMAIL to asha@example.com: Your order 104 is confirmed Order 105 saved, amount Rs 349.50 SMS to 98450 12345: Your order 105 is confirmed Order 106 saved, amount Rs 10.00 Test check: messages recorded = 1 Test check: test@example.com -> Your order 106 is confirmed
What this code does
- The same
OrderServiceclass sends an email, then an SMS. Only the object passed to the constructor changed. - The third service gets a
FakeNotifier. Nothing is sent; the test readsfake.sentto check what would have been sent.
Example 5 · Old callers stop compiling, and that is useful
interface Notifier { void send(String to, String message);}
class EmailNotifier implements Notifier { public void send(String to, String message) { System.out.println("EMAIL to " + to + ": " + message); }}
class OrderService { private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; }
void placeOrder(int orderId, String contact) { notifier.send(contact, "Your order " + orderId + " is confirmed"); }}
public class OldCallerDemo { public static void main(String[] args) { OrderService service = new OrderService(); // old code, written before the change service.placeOrder(107, "asha@example.com"); }}OldCallerDemo.java:25: error: constructor OrderService in class OrderService cannot be applied to given types;
OrderService service = new OrderService(); // old code, written before the change
^
required: Notifier
found: no arguments
reason: actual and formal argument lists differ in length
1 errorWhat this code does
- This is the real
javacmessage.required: Notifier/found: no argumentssays the constructor now needs a notifier. - Fix it by passing one:
new OrderService(new EmailNotifier()). Each call site now makes the choice openly.
To inject a dependency is simply to hand it in from outside. OrderService now says only "I need some Notifier", and the code that creates the service decides which one: new OrderService(new SmsNotifier()). A test passes a FakeNotifier that writes messages into a list, so nothing is sent and the test can check exactly what would have been sent.
Objects.requireNonNull in the constructor stops a null at the moment the object is built, with a clear message, instead of a confusing NullPointerException later inside placeOrder.
Order of execution
Refactor to constructor injection
Put the refactoring steps in the right order.
Notifier, every old new OrderService() stops compiling. That is good. The compiler shows you every place that must now decide which notifier to pass.Tight vs loose coupling side by side
Loose coupling means a class depends only on an interface and receives the real object from outside, so either side can change without touching the other.
Example 6 is a college hostel fee reminder written twice, once tight and once loose. Only the place of the new differs.
Example 6 · Tight and loose fee reminders in one program
interface Notifier { void send(String to, String message);}
class EmailNotifier implements Notifier { public void send(String to, String message) { System.out.println(" EMAIL to " + to + ": " + message); }}
class SmsNotifier implements Notifier { public void send(String to, String message) { System.out.println(" SMS to " + to + ": " + message); }}
class WhatsAppNotifier implements Notifier { public void send(String to, String message) { System.out.println(" WHATSAPP to " + to + ": " + message); }}
// Tight: the class decides which notifier to useclass TightFeeReminder { void remind(String student, String contact, int dueAmount) { Notifier notifier = new EmailNotifier(); notifier.send(contact, student + ", hostel fee of Rs " + dueAmount + " is due"); }}
// Loose: whoever creates the class decidesclass LooseFeeReminder { private final Notifier notifier;
LooseFeeReminder(Notifier notifier) { this.notifier = notifier; }
void remind(String student, String contact, int dueAmount) { notifier.send(contact, student + ", hostel fee of Rs " + dueAmount + " is due"); }}
public class CouplingSideBySideDemo { public static void main(String[] args) { System.out.println("Tight coupling: always email"); new TightFeeReminder().remind("Kiran", "kiran@example.com", 18000);
System.out.println("Loose coupling: the caller picks"); new LooseFeeReminder(new EmailNotifier()).remind("Kiran", "kiran@example.com", 18000); new LooseFeeReminder(new SmsNotifier()).remind("Kiran", "98860 11223", 18000); new LooseFeeReminder(new WhatsAppNotifier()).remind("Kiran", "98860 11223", 18000); }}Tight coupling: always email EMAIL to kiran@example.com: Kiran, hostel fee of Rs 18000 is due Loose coupling: the caller picks EMAIL to kiran@example.com: Kiran, hostel fee of Rs 18000 is due SMS to 98860 11223: Kiran, hostel fee of Rs 18000 is due WHATSAPP to 98860 11223: Kiran, hostel fee of Rs 18000 is due
What this code does
TightFeeRemindercan only email, because its method saysnew EmailNotifier().LooseFeeReminderis written once and used with three channels. AddingWhatsAppNotifierneeded no change to the reminder class.
The tight version can only email. The loose version can email, send an SMS or a WhatsApp message, and the class itself is never edited; a fourth channel is one new class that implements Notifier.
Side by side:
- Tight:
new EmailNotifier()inside the class. To change it, edit the class. To test it, send real messages. - Loose:
Notifiercomes in through the constructor. To change it, pass another object. To test it, pass a fake. - The price of loose coupling: somebody outside must now create the objects and connect them. The next lesson is about that somebody.
Next step
Check your understanding
12 quick questions