Video in progress
Explain the difference between coupling and cohesion. Which should be low and which high?
Coupling is how strongly modules depend on each other; it should be low. Cohesion is how well the things inside one module serve a single purpose; it should be high. The goal: "loose coupling, high cohesion".
📖 Answer
You can tell coupling is high when:
- one class reaches into another's internal fields or creates its concrete implementation with
new; - one change requires editing dozens of files;
- there are long chains like
a.getB().getC().getD().doSomething().
When cohesion is low:
- a
CommonUtilsclass has date formatting, file reading and SMS sending together; - the methods use different parts of the class's fields, with almost nothing in common.
An example:
// low cohesion: everything mixed together
class Helper {
static String formatPhone(String p) { ... }
static byte[] resizeImage(byte[] img) { ... }
static long calcPenalty(Loan l) { ... }
}
Move these methods to their own areas: PhoneFormatter, ImageResizer, Loan.penalty().
The two ideas are related: when cohesion goes up, coupling usually goes down, because things that belong together sit in one place and fewer "wires" run between modules.
A practical check: look at how many packages or modules you have to open for a single business change.
Sign up to mark studied questions and save your progress.