Hitchhiker's Guide to Software Architecture and Everything Else - by Michael Stal

Wednesday, October 21, 2020

 Cohesion and Coupling

Sometimes what appears to be very simple and clear, is not that clear at all. A prominent example is the difference between cohesion and coupling.
    • Cohesion indicates the relationships between components in a module. These relationships are not just syntactic sugar but have a semantic implication.  For example, if a module provides different separate functionalities it will reveal low cohesion. In constrast, modules with high cohesion implement functionalities that are tightly interweaved with each other.  In other words, modules with a low cohesion provide different things that are not related with each other. Thus, they violate the SRP principle (SRP = Single Responsibility Principle). The best refactoring in such cases is to split up the module into different modules that obey the SRP.
    • Coupling defines the number of relationships between different modules. A module A that introduces a lot of relations to module B, strongly depends on module B, and vice versa. Strong respectively tight coupling of modules indicates that functionalities in B could be integrated in A. The obvious refactoring would integrate all functionalities of B into A, thus decreasing coupling of the system. Of course, merging of modules might reduce cohesion in the resulting module A. But what if another module A* also depends heavily on B. Should we then merge A and B as well as A* and B? Or should we merge A and B and reroute (A*, B) relations to A, thus possibly increasing coupling between A and A*? The best option is to strive for high cohesion and low coupling throughout our system and its constituting modules. Merging B into A and A* at the same time might violate the DRY principle (Don‘t repeat Yourself). But as we know, the DRY principle is not always appropriate. In Microservices architectures the diffenent microservices should hide their implementation details and do not share the same information but be independent of each other. Nonetheless, the principles of high cohesion and low coupling still apply.
Fortunately, architecture introspection tools can visualize cohesion and coupling and even provide hints and mechanisms how to restructure a given system.