We now know how to build classes and connect them: through inheritance, interfaces, association, aggregation and composition. But knowing how to connect classes raises a design question: how much should they be connected, and how should the work be divided among them?
Two classic measures from the structured design movement of the 1970s (the work of Wayne Stevens, Glenford Myers and Larry Constantine, later popularised by Ed Yourdon and Constantine's book Structured Design) answer that question, and they are still used in design reviews today: coupling and cohesion.
Coupling is the degree of dependence between two modules (classes): how much one needs to know about, and is affected by, the other. Cohesion is the degree to which the elements inside one module (its fields and methods) belong together and work toward a single purpose.
The goal is short enough to memorise:
Low coupling, high cohesion.
Think of a well-run hospital. Each department (cardiology, radiology, billing) is highly cohesive: everything inside it is about one job. Departments are loosely coupled: cardiology sends a request form to radiology and gets a report back, without knowing how the X-ray machine works. If radiology replaces its machine, cardiology does not have to change anything.
Why These Two Ideas Matter
Benefit | From low coupling | From high cohesion |
|---|---|---|
Change | A change in one class rarely forces changes in others (no "ripple effect") | A change in one feature touches one class, not ten |
Understanding | You can read a class without reading all its neighbours | A class's name tells you what is inside |
Testing | A class can be tested alone, with fakes for its dependencies | Small, focused classes need small, focused tests |
Reuse | A class that does not drag ten others along can be reused | A class that does one thing is useful in many places |
The two usually move together. When responsibilities are scattered randomly (low cohesion), every class needs pieces of every other class (high coupling). Grouping related things together raises cohesion and, as a side effect, lowers coupling.
Coupling: Tight vs Loose
A tightly coupled class
An online shop's OrderService confirms orders by email:
class EmailSender {
void sendEmail(String to, String text) {
System.out.println("[SMTP] to " + to + ": " + text);
}
}
class OrderService {
private final EmailSender sender = new EmailSender(); // chooses its own concrete helper
void placeOrder(String customer, double amount) {
System.out.println("Order saved: " + customer + ", Rs. " + amount);
sender.sendEmail(customer, "Your order is confirmed");
}
}
public class TightDemo {
public static void main(String[] args) {
new OrderService().placeOrder("asha@example.com", 499.0);
}
}Output:
Order saved: asha@example.com, Rs. 499.0
[SMTP] to asha@example.com: Your order is confirmedIt works. But OrderService creates a specific EmailSender itself, so:
Switching to SMS (or sending both) means editing
OrderService, even though ordering logic has not changed.Testing
placeOrderreally sends emails, because there is no way to plug in anything else.Any change to
EmailSender's method names or constructor ripples intoOrderService.
Loosening the coupling
Two changes fix this: depend on an interface instead of a concrete class (as in Abstract Classes vs Interfaces), and let someone else hand in the object through the constructor (called dependency injection).
import java.util.ArrayList;
import java.util.List;
interface Notifier { // the only thing OrderService knows about
void notify(String to, String text);
}
class EmailNotifier implements Notifier {
@Override public void notify(String to, String text) {
System.out.println("[SMTP] to " + to + ": " + text);
}
}
class SmsNotifier implements Notifier {
@Override public void notify(String to, String text) {
System.out.println("[SMS] to " + to + ": " + text);
}
}
class FakeNotifier implements Notifier { // for tests: just remembers messages
final List<String> sent = new ArrayList<>();
@Override public void notify(String to, String text) { sent.add(to + "|" + text); }
}
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { // the dependency is handed in
this.notifier = notifier;
}
void placeOrder(String customer, double amount) {
System.out.println("Order saved: " + customer + ", Rs. " + amount);
notifier.notify(customer, "Your order is confirmed");
}
}
public class LooseDemo {
public static void main(String[] args) {
new OrderService(new EmailNotifier()).placeOrder("asha@example.com", 499.0);
new OrderService(new SmsNotifier()).placeOrder("+91-98xxxxxx01", 250.0);
FakeNotifier fake = new FakeNotifier();
new OrderService(fake).placeOrder("test-user", 1.0);
System.out.println("Test check: " + fake.sent);
}
}Output:
Order saved: asha@example.com, Rs. 499.0
[SMTP] to asha@example.com: Your order is confirmed
Order saved: +91-98xxxxxx01, Rs. 250.0
[SMS] to +91-98xxxxxx01: Your order is confirmed
Order saved: test-user, Rs. 1.0
Test check: [test-user|Your order is confirmed]OrderService now knows only one method, notify(to, text). Email, SMS and a test fake all plug in without changing a single line of it. This idea of depending on abstractions rather than concrete classes is formalised as the Dependency Inversion Principle, covered in SOLID: Interface Segregation & Dependency Inversion.
Tight: OrderService ───────────────► EmailSender (knows the concrete class)
Loose: OrderService ───► «interface» Notifier
▲ ▲ ▲
EmailNotifier SmsNotifier FakeNotifierNote that loose coupling is not zero coupling. Classes must collaborate, so some dependence is unavoidable. The aim is to depend on as little as possible, and on things that change rarely.
Types of Coupling (Worst to Best)
Structured design classifies the ways two modules can depend on each other. In OOP, read "module" as "class" or "method". This ordering is a favourite exam question.
Type | What the modules share | Example |
|---|---|---|
Content (worst) | One module directly reads or changes another's internal data or code |
|
Common | Both read and write the same global data | Several classes use a public static mutable |
External | Both depend on an externally imposed format, protocol or device | Two classes both parse the same CSV file layout or a printer's command set |
Control | One passes a flag that decides what the other does internally |
|
Stamp | A whole data structure is passed, but only part of it is used |
|
Data (best) | Only the elementary values actually needed are passed as parameters |
|
Some books add message coupling as an even lower level, where objects interact only by calling each other's public methods with no shared data at all, and no coupling for modules that do not interact. Memorise the main ladder:
content > common > external > control > stamp > data
(tightest, worst) (loosest, best)Content coupling
class Cart {
public List<Double> items = new ArrayList<>(); // internals exposed
public double total; // must always equal the sum of items
}
class Checkout {
void applyCoupon(Cart cart) {
cart.total = cart.total - 100; // edits Cart's internal state directly
cart.items.clear(); // and its internal list
}
}Checkout depends on exactly how Cart stores things, and can break Cart's rule that total equals the sum of items. If Cart changes its internals, Checkout breaks. The cure is encapsulation: private fields and methods like cart.applyDiscount(100) (see Access Modifiers).
Common coupling
class AppState {
public static double discountPercent = 10; // global, mutable
}
class PriceCalculator {
double finalPrice(double p) { return p - p * AppState.discountPercent / 100; }
}
class FestivalSale {
void start() { AppState.discountPercent = 50; } // silently changes every price
}PriceCalculator and FestivalSale never mention each other, yet a change in one alters the behaviour of the other. This hidden link is why Static vs Instance Members warned about mutable static state. The cure: pass the discount in, or give both an object that owns it.
Control coupling
// Control coupled: the caller steers the callee's internal logic
class ReportPrinter {
void print(String data, int mode) { // mode: 1 = screen, 2 = PDF, 3 = email
if (mode == 1) { /* show on screen */ }
else if (mode == 2) { /* make PDF */ }
else if (mode == 3) { /* email it */ }
}
}
// Better: separate operations (or separate classes behind one interface)
class ReportPrinter2 {
void printToScreen(String data) { }
void exportPdf(String data) { }
void email(String data) { }
}The caller must know the meaning of the magic numbers, which are really the callee's internal choices. Adding a fourth mode means changing both. Replacing flags with separate methods or with polymorphism (one class per output kind) removes the control coupling.
Stamp coupling vs data coupling
class FeeCalculatorStamp {
double fee(Student s) { return s.credits * 1500.0; } // needs only credits
}
class FeeCalculatorData {
double fee(int credits) { return credits * 1500.0; } // gets exactly what it needs
}The stamp-coupled version depends on the whole Student class: rename its fields or move it to another package and the fee code is affected, and you cannot compute a fee without building a full student. The data-coupled version depends on one integer. Stamp coupling is not always wrong (passing a well-designed object is often cleaner than ten parameters), but pass what the method actually needs.
Cohesion: Does This Class Do One Thing?
A class with high cohesion has a clear, single purpose, and its methods work together on its own data. A class with low cohesion is a drawer of unrelated things.
import java.util.List;
// LOW cohesion: unrelated jobs in one class (shown only for comparison, not used)
class StudentHelper {
double average(List<Integer> marks) { return 0; } // grading
String toPdf(String report) { return report; } // formatting
void sendMail(String to) { } // networking
String todayAsText() { return ""; } // dates
}
// HIGH cohesion: each class does one thing, and every method uses the class's data
class GradeBook {
private final List<Integer> marks;
GradeBook(List<Integer> marks) { this.marks = List.copyOf(marks); }
double average() {
return marks.stream().mapToInt(Integer::intValue).average().orElse(0);
}
int highest() {
return marks.stream().mapToInt(Integer::intValue).max().orElse(0);
}
String grade() {
double avg = average();
if (avg >= 90) return "O";
if (avg >= 75) return "A";
if (avg >= 60) return "B";
return "C";
}
}
class ReportFormatter {
String format(String name, GradeBook g) {
return String.format("%s | avg %.1f | best %d | grade %s",
name, g.average(), g.highest(), g.grade());
}
}
public class CohesionDemo {
public static void main(String[] args) {
GradeBook g = new GradeBook(List.of(82, 91, 76, 88));
System.out.println(new ReportFormatter().format("Asha", g));
}
}Output:
Asha | avg 84.3 | best 91 | grade AStudentHelper mixes grading, document formatting, networking and dates. Changing the email server, the PDF layout or the grading rules all mean editing the same class, and anyone who needs one of these jobs drags in the others. GradeBook does only grading, and every method uses its marks; ReportFormatter only formats. Each class has one reason to change, which is exactly the Single Responsibility Principle covered in SOLID: Single Responsibility & Open/Closed.
A practical smell test: if you cannot describe what a class does in one sentence without the word "and", or if its name is vague (Manager, Helper, Utils, Misc), its cohesion is probably low.
Types of Cohesion (Worst to Best)
Structured design also ranks seven kinds of cohesion, from weakest to strongest:
Type | Elements are grouped because… | Example |
|---|---|---|
Coincidental (worst) | No real reason; they just ended up together |
|
Logical | They do the same category of thing; a flag picks which one runs |
|
Temporal | They run at the same time |
|
Procedural | They follow a fixed order of steps, possibly on different data | "check login, then load menu, then play sound" |
Communicational | They work on the same data | Methods that all read one student record: print it, compute CGPA, find backlogs |
Sequential | The output of one is the input of the next | read marks → compute average → assign grade |
Functional (best) | Everything contributes to one well-defined task |
|
coincidental < logical < temporal < procedural < communicational < sequential < functional
(weakest, worst) (strongest, best)A memory aid built from the first letters (C, L, T, P, C, S, F): "Can Lazy Teachers Prepare Clear, Simple Functions?"
Notice how the two ladders connect: a logically cohesive module almost always needs a flag to choose what to do, which forces its callers into control coupling. Poor cohesion inside a class shows up as poor coupling between classes.
Some authors also measure class cohesion with metrics such as LCOM (Lack of Cohesion of Methods), which, roughly speaking, looks at how many pairs of methods share no fields. A high LCOM hints that the class is really two or more classes glued together.
Practical Techniques
Keep fields private and expose operations, not data. This rules out content coupling.
Program to interfaces, and receive dependencies through constructors instead of creating them with
newinside the class.Avoid mutable globals (public static non-final fields). This rules out common coupling.
Replace flag parameters with separate methods or polymorphism.
Pass what is needed, not whole objects "just in case".
Talk to neighbours, not strangers (the Law of Demeter):
order.customer().wallet().debit(x)couples you to three classes;order.chargeCustomer(x)couples you to one.Split classes whose methods form separate groups that do not share data. Name each new class after its single purpose.
Common Mistakes
Mixing up the two definitions. Coupling is between modules; cohesion is within a module.
Reversing the goal. We want low coupling and high cohesion, never the other way round.
Reversing the ladders. Content coupling is the worst coupling; data coupling is the best. Coincidental cohesion is the worst cohesion; functional is the best.
Chasing zero coupling. A program whose classes never interact does nothing. Aim for few, narrow, stable dependencies.
Over-splitting. Twenty one-line classes that must always be used together are not "highly cohesive"; the knowledge has just been scattered, and coupling rises. Group things that change together.
Thinking an interface alone fixes coupling. If the class still does
new EmailNotifier()internally, it is still tied to that concrete class.
Interview and GATE-Style Questions
Q1. Arrange in increasing order of coupling strength (best design first): control, content, data, stamp, common, external.
data < stamp < control < external < common < content.
Q2. Which is the most desirable cohesion, and which the least?
Functional cohesion is the most desirable; coincidental cohesion is the least.
Q3. A module initialise() opens the log file, resets counters and connects to the database because all of these must happen at program start. Which cohesion is this?
initialise() opens the log file, resets counters and connects to the database because all of these must happen at program start. Which cohesion is this?Temporal cohesion: the tasks are grouped only because they happen at the same time.
Q4. Module A passes a boolean isAdmin to module B, and B uses it to decide which branch of code to run. What type of coupling is this?
isAdmin to module B, and B uses it to decide which branch of code to run. What type of coupling is this?Control coupling: A passes control information that directs B's internal logic.
Q5. Two modules both read and update a global variable. What type of coupling is this, and why is it harmful?
Common coupling. Any module can change the shared data, so a change in one module can break another that never calls it; bugs are hard to trace, and the modules cannot be reused or tested independently.
Q6. Why does "low coupling, high cohesion" make software easier to maintain?
High cohesion puts everything related to one responsibility in one place, so a change is local. Low coupling means other modules depend only on narrow, stable interfaces, so that local change does not ripple outward. Together they limit how much of the system one change can affect.
Q7. In the tight OrderService example, name two concrete changes that reduce coupling.
OrderService example, name two concrete changes that reduce coupling.(1) Make OrderService depend on an interface such as Notifier instead of the concrete EmailSender. (2) Pass the notifier in through the constructor (dependency injection) rather than creating it with new inside the class.
Summary
Coupling = dependence between modules. Aim low.
Cohesion = how well the parts within a module belong together. Aim high.
Coupling, worst to best: content, common, external, control, stamp, data (some books add message coupling below data).
Cohesion, worst to best: coincidental, logical, temporal, procedural, communicational, sequential, functional.
Lower coupling with encapsulation, interfaces, constructor injection, no mutable globals, no flag parameters, and passing only needed data.
Raise cohesion by giving each class one purpose and one reason to change; split "Helper" and "Manager" classes.
These two ideas are the foundation for the SOLID principles and design patterns in the coming chapters.
Each class should do one thing well (high cohesion) and know as little as possible about the others (low coupling).