Is there a metric analogous to the McCabe Complexity measure to measure how cohesive a routine is and also how loosely (or tightly) coupled the routine is to other code in the same code base?
-
related: [How do you balance out code structuring (few big functions vs. many small ones)?](http://programmers.stackexchange.com/q/201130/31260) – gnat Mar 23 '15 at 10:58
2 Answers
I think the metric you are looking for is LCOM4, although it applies more to classes.
Sonar explains it nicely here:
...metric : LCOM4 (Lack Of Cohesion Methods) to measure how cohesive classes are. Interpreting this metric is pretty simple as value 1 means that a class has only one responsibility (good) and value X means that a class has probably X responsibilities (bad) and should be refactored/split.
There is not any magic here, only common sense. Let’s take a simple example with class Driver. This class has two fields : Car and Brain, and five methods : drive(), goTo(), stop(), getAngry() and drinkCoffee(). Here is the dependency graph between those components. There are three blocks of related components, so LCOM4 = 3, so the class seems to have three different responsibilities and breaks the Single Responsibility Principle.
...
It's a great tool, if you can use it. :)
-
-
Just too bad they don't go into how they calculate the metric. – Onorio Catenacci May 31 '12 at 15:44
-
3This might help with that: http://www.aivosto.com/project/help/pm-oo-cohesion.html – Oleksi May 31 '12 at 15:46
-
Out of curiosity, how would you refactor that diagram to obey the Single Responsibility Principle? `brain.setAngry(driver)`? `car.applyBreaks(driver)`? – Phil Nov 21 '13 at 20:24
-
I doubt that code-based cohesion metrics can truly be indicative of interface level cohesion, and may even promote bad programming: http://mortoray.com/2015/04/29/cohesion-and-coupling-good-measures-of-quality/#comment-20266 – edA-qa mort-ora-y May 04 '15 at 08:23
-
This is conflating `internal` cohesion that should be exhibited within the structure of a class vs `external` cohesion that should be exhibited by closely collaborating components (in particular by those residing within a module or layer or that mediate the boundaries between modules and layers.) For the later, I would suggest to rely on connascence and and instability/coupling metrics. – luis.espinal May 23 '17 at 14:55
-
- Afferent coupling: Number of responsibilities
- Efferent coupling: Number of dependencies
- Instability: Ratio of efferent coupling to total coupling (Afferent + Efferent).
Instability is supported in various code metric tools.

- 4,480
- 1
- 22
- 37
-
Thanks @Brian--exactly the sort of thing I was hoping to find. – Onorio Catenacci May 31 '12 at 15:05