May 2, 2017
20 Dev Metrics - 12. CohesionThe 12th metric in my 20 Dev Metrics series - Cohesion - helps us to reduce coupling between classes and components/packages/services encapsulating those dependencies as much as possible. The rule of thumb is things that change together belong together.
In a class, we're interested in the extent to which features of that class reference other features of the same class - e.g., methods that use fields, methods that call other methods in the same class. A classic metric along these lines is 'Lack of Cohesion of Methods' - the extent to which methods don't belong in the same class - but experience has taught me that this is a confusing metric.
I recommend measuring cohesion, and not the lack of it. Relational Cohesion of a class can be calculated by counting all the internal references, and then dividing that by the number of methods (including constructors). Essentially, it's the average number of internal relationships per method.
Likewise for packages, count the number of internal relationships between classes/modules in the same package, and divide by the number of classes/modules - giving us the average number of internal relationships per class.
If we want to localise the impact of making changes, we should aim to reduce coupling between classes and packages by increasing their cohesion.
Posted 1 year, 8 months ago on May 2, 2017