A customer orders medicines on a pharmacy app. The app checks the prescription for any medicine that needs one, checks the stock, books a delivery slot and sends an SMS. The code for these four jobs can be arranged well or badly.
Coupling is how much one class must know about another. Cohesion is how much the things inside one class belong together. We want low coupling and high cohesion.
The idea
Class A is coupled to class B when a change to B can force a change to A. The more A knows about B, the more of B's changes reach A. A class that calls stock.isAvailable(medicine, 2) knows one method. A class that reads another class's map, and knows that its key is the medicine name and its value is a count of units, knows the insides. The first is low coupling, and the second is high coupling.
A class is cohesive when its fields and methods serve one purpose and change together. A simple check is to ask which fields each method uses. If the methods share the same few fields, the class is cohesive. If the methods fall into groups that never share a field, the class is several classes in one file.
The two usually move together. When the code for one job sits in one class, other classes need only a few of its methods, so coupling falls as cohesion rises.
Two readings of this idea are wrong. Low coupling does not mean zero dependencies. A checkout must use the stock, and the aim is that it uses a few methods, not the insides. High cohesion does not mean the smallest possible classes either.
Example: an online pharmacy order
The first version puts all four jobs in one class, and leaves the data public so that other classes can use it:
import java.util.*; public class OrderManager { public final Set<String> prescriptionOnly = new HashSet<>(); public final Map<String, Integer> stock = new HashMap<>(); public final Deque<String> freeSlots = new ArrayDeque<>(); private final SmsGateway sms; public OrderManager(SmsGateway sms) { this.sms = sms; } public boolean needsPrescription(String medicine) { return prescriptionOnly.contains(medicine); } public String bookSlot() { return freeSlots.poll(); } public void sendSms(String phone, String text) { sms.send(phone, text); }}We check which fields each method uses. needsPrescription reads only prescriptionOnly, bookSlot reads only freeSlots, and sendSms uses only sms. No method touches two of these fields, so the class has low cohesion.
The stock has no method at all, so other classes use the map directly. CartPage reads it:
public class CartPage { private final OrderManager manager; public CartPage(OrderManager manager) { this.manager = manager; } public boolean canAdd(String medicine, int quantity) { return manager.stock.getOrDefault(medicine, 0) >= quantity; }}CheckoutService subtracts from the map with manager.stock.merge(medicine, -quantity, Integer::sum). Both classes know that stock is a Map, what its key is and what its value means. That is high coupling.
Then a change request arrives. The pharmacy moves its stock to a warehouse system, and the app must ask that system through a WarehouseClient instead of keeping its own map.
CartPage and CheckoutService must be rewritten to call the client. OrderManager changes too, and its prescription, slot and SMS code sits in that same file, so it must be tested again. One change about stock edits three classes.
Regrouped
We give each job its own class, keep each class's data private, and delete OrderManager. PrescriptionRules, DeliverySlots and OrderSms each hold the one field that OrderManager kept for them. Stock gets a class with methods for what its callers need:
import java.util.HashMap;import java.util.Map; public class StockService { private final Map<String, Integer> unitsByMedicine; public StockService(Map<String, Integer> openingStock) { this.unitsByMedicine = new HashMap<>(openingStock); } public boolean isAvailable(String medicine, int quantity) { return unitsByMedicine.getOrDefault(medicine, 0) >= quantity; } public void reserve(String medicine, int quantity) { if (!isAvailable(medicine, quantity)) { throw new IllegalStateException("Not enough " + medicine); } unitsByMedicine.merge(medicine, -quantity, Integer::sum); }}Every method uses unitsByMedicine, so the class is cohesive. CartPage.canAdd now calls stock.isAvailable(medicine, quantity), and CheckoutService calls stock.reserve(...). Neither class knows that a map exists. A getStock() method that returned the map would not help, because callers would still know that stock is a map.
CheckoutService now depends on four classes instead of one, but it calls one method on each: needsPrescription, reserve, book (which was bookSlot) and confirm. Each dependency is a single method, and that is low coupling.
Now the same change arrives. The map in StockService becomes a WarehouseClient field, passed in through the constructor. isAvailable asks warehouse.unitsOf(medicine), and reserve calls warehouse.hold(medicine, quantity). CartPage, CheckoutService, PrescriptionRules, DeliverySlots and OrderSms do not change.
Splitting too far
Suppose someone splits StockService into StockChecker and StockReserver, one method each. Both need the same map, so the map moves into a third class, StockData, as a public field, unitsByMedicine. Each class now does one small thing, and each one is coupled to the insides of StockData.
When the stock moves to the warehouse, all three classes change. They share one piece of data, so they are one job, and they belong in one class.
The Single Responsibility Principle reaches the same answer from another side. It splits classes by who asks for changes, and it keeps one person's rules in one class.
When not to
A short script that one person writes and changes does not need this care. If the pharmacy app has one screen and one developer, a single OrderManager with private fields is fine. Private fields cost almost nothing, so we use them from the start. Splitting can wait until a class's methods fall into groups that share no data, or until a second class needs something from inside it.
In an interview
When you draw a class, say which fields each method uses and which classes call it. If the methods fall into groups, split the class there. If a caller needs another class's field, add a method that answers the caller's question instead. The Parking Lot design keeps the fee in a PricingStrategy, so ParkingLot calls feeFor and never sees a tariff.
Common mistakes:
- Public fields for convenience. Every class that reads one is coupled to how the data is stored. The Encapsulation page shows how to hide them.
- A
UtilsorManagerclass that holds every job. Its methods share no data, so it has low cohesion, and every change edits it. - Tiny classes that share one piece of data. They are one job spread over several files, and one change edits all of them.
Summary
- Coupling is how much one class must know about another. Cohesion is how much the things inside one class belong together.
- We aim for low coupling and high cohesion: each job in one class, used by other classes through a few methods.
- Low coupling does not mean zero dependencies. Depending on a method that answers the caller's question is fine. Depending on another class's data, through its fields or a getter that hands them out, is not.
- If the methods of a class share no data, split it. If tiny classes share one piece of data, merge them.