From "Fundamentals of Software Architecture"
🎧 Listen to Summary
Free 10-min PreviewCohesion: Definition and Measurement
Key Insight
Cohesion measures the degree to which parts within a module are related and should remain together. An ideally cohesive module contains all necessary parts to function, where separating them would increase coupling and reduce readability. Computer scientists categorize cohesion into seven types, ranging from most desirable to least. Functional cohesion, the best, means every part is essential and related to the module's core function. Sequential and communicational cohesion involve data flow or communication chains between parts. Procedural cohesion implies execution order dependencies, while temporal cohesion links tasks by timing, like system startup initializations.
Logical cohesion occurs when data within a module is related logically but not functionally; an example is a 'StringUtils' package with static methods operating on strings but otherwise unrelated. Coincidental cohesion, the worst form, describes elements in a module that are unrelated except for their physical presence in the same source file. Determining the optimal level of cohesion can be subjective, requiring architects to analyze trade-offs. For example, deciding if 'get customer orders' and 'cancel customer orders' belong in a 'Customer Maintenance' module or a separate 'Order Maintenance' module depends on factors like expected module growth and potential coupling implications.
Despite cohesion's subjectivity, metrics exist to identify a lack of cohesion. The Lack of Cohesion in Methods (LCOM) metric measures a module's structural cohesion, typically for components. The LCOM score increases when methods within a class do not share common fields, indicating poor cohesion. For example, if a class has private fields 'a' and 'b', and many methods access only 'a' while others access only 'b', the LCOM score will be high. This metric helps architects find incidentally coupled classes that might be better as separate entities. While useful for analyzing codebases during architectural migrations or technical debt assessment, LCOM primarily reveals structural issues and cannot determine logical cohesion, highlighting a limitation common to many code-level metrics.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Fundamentals of Software Architecture summary with audio narration, key takeaways, and actionable insights from Mark Richards, Neal Ford.