Video in progress
How do you tell that a class has low cohesion? What signs and metrics are there?
If a class's fields split into groups and each method uses only one of those groups, cohesion is low. Signs: a name you can only describe with "and", lots of dependencies, code that changes for different reasons. LCOM is the usual metric.
📖 Answer
Practical signs:
- the class is called
Manager,Helper,UtilsorProcessorand its description is "registers the user and sends the report and clears the cache"; - 7–10 dependencies in the constructor, but each method uses only 1–2 of them;
- in the git history the class keeps changing for different tickets (payments, reports, auth);
- in tests, half of the mocks are left as
nullfor each test because they aren't needed.
The metric is LCOM (Lack of Cohesion of Methods). The simple variant (LCOM4): treat methods as graph nodes and connect methods that use the same field or call each other. The number of connected components is LCOM4. 1 is good; 3 means the class is really 3 classes.
class UserService {
private final UserRepository users; // group A
private final PasswordEncoder encoder; // group A
private final ReportClient reports; // group B
private final CacheManager cache; // group C
void register(...) { users..., encoder... }
void changePassword(...) { users..., encoder... }
void sendMonthly(...) { reports... }
void evictAll() { cache... }
}
// LCOM4 = 3 → it should be split into three classes
Tools: SonarQube (cognitive complexity, class size), IntelliJ's "Dependency Structure Matrix", the MetricsReloaded plugin. Don't cling to the numbers: they only show where to look. The final question is still "does this class have one clear job?"
Sign up to mark studied questions and save your progress.