- Why Metrics Matter
- Cyclomatic Complexity
- Coupling Metrics
- Combination Measures
- Conclusion
Coupling Metrics
The coupling metrics of efferent and afferent coupling help understand how likely a defect in one class will "ripple" across a system. A systema computer software system, or frankly, any other type of systemthat has low coupling tends to be more stable than one that has high coupling. These metrics, defined by Robert C. Martin in his book Agile Software Development: Principles, Patterns, and Practices, are the key to measuring overall coupling in a software system.
Efferent Coupling
Efferent coupling measures the number of classes on which a given class depends. A good way to remember efferent (versus afferent) is that classes with high efferent coupling will receive the effects of changes or defects in other classes. It is a likely place where a bug, introduced in one place, will manifest.
Sometimes, the nature of a component will drive a higher level of efferent coupling. Classes that perform activities such as orchestration tend to end up in this category, because part of their function is that they need to be able to work with multiple other classes to get things done. Splitting out responsibilities can help reduce coupling, but in reality, there are some components whose nature is going to demand at least a moderate level of efferent coupling.
Afferent Coupling
Afferent coupling measures how many classes depend on a given class. Just as with efferent coupling, a good way to remember afferent is that classes with high afferent will affect other classes when changes are made.
This type of coupling may simply be the end result of doing a good job in the area of code reuse. Like efferent coupling, in the case of classes that perform orchestration, afferent coupling in the case of classes that have important responsibilities in a system is not always bad.
For any one class, a high amount of either type of coupling is a mere signal that there might be an issue, not an iron-clad indicator. More troubling is when such coupling is high across an entire system.
Instability Index
The instability index is measures efferent coupling in relation to total coupling. If you have high afferent coupling but no efferent coupling, it is still reasonable to assume that particular class is stable. A class that, on the other hand, has high efferent and high afferent values tends to be the medium through which bugs ripple. If bugs were a disease, the class with both high afferent and efferent complexity would be the kid with a runny nose who ends up at the daycare that your kids attend. It is measured using the formula:
- Ce / (Ce + Ca)
Where Ce is efferent coupling and Ca is afferent coupling. A value of 1 means it is highly unstable, and a value of 0 means it is stable.