36

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?

Onorio Catenacci
  • 2,977
  • 3
  • 28
  • 38

2 Answers2

31

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. https://i.sstatic.net/2527G.png

...

It's a great tool, if you can use it. :)

gnat
  • 20,543
  • 29
  • 115
  • 306
Oleksi
  • 11,964
17
  • 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.

Brian
  • 4,553