CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 1 min read

Measuring cohesion

Which methods use which fields.

CC gives a simple way to judge a class. Each method should use one or more of the class's fields. The more fields a method uses, the more it belongs to the class. A class where every method uses every field is as cohesive as it can be. Nobody expects that in real code, but the closer, the better.

CC shows a small stack class with two fields: a counter for the top and a list of elements. Of its three methods, only size() leaves one field unused. That class is very cohesive.

Now picture the opposite. A BookingManager has fields for rooms, emailServer and reportFormat. Methods about booking use only rooms. Methods about alerts use only emailServer. Methods about printing use only reportFormat. Three groups of methods use three groups of fields and never meet. This is really three classes inside one.

CC gives a rule of thumb: when some fields are used by only a subset of the methods, another class is trying to get out. Split the class so that each part has fields and methods that belong together.

A caution follows. Splitting large functions into small ones often produces many fields that only some functions use. CC says that this also shows a hidden class. The cure is to pull the group out into its own class, and the result is more small classes, each cohesive.

Check yourself: 1. In BookingManager, how many hidden classes are there? 2. What does a field used by only some methods suggest?