Cohesion & Coupling
In software engineering, cohesion and coupling are two of the most important principles for evaluating the quality of a software architecture. The goal of a good design is to achieve high cohesion and low coupling.
quadrantChart title Cohesion vs. Coupling x-axis Low Coupling --> High Coupling y-axis Low Cohesion --> High Cohesion quadrant-1 Unmaintainable quadrant-2 Difficult to Reuse quadrant-3 Ideal quadrant-4 Hard to Maintain points
| Concept | Definition | Analogy | Goal |
|---|---|---|---|
| Cohesion | A measure of how well the internal elements of a module are related and focused on a single, well-defined task. | The unity of a football team. Each player has a specific function that contributes to the common goal. | High |
| Coupling | The degree of interdependence between different modules. It measures how much a change in one module will affect others. | The connections between a train’s cars. Strong links (high coupling) can limit flexibility and cause a ripple effect when changes are made. | Low |
1. Cohesion: The “Inner Strength” of a Module
Cohesion is a qualitative measure of a module’s focus. The more a module has one unique responsibility, the stronger its cohesion. A highly cohesive module is easier to understand, test, and reuse.
Cohesion Levels (from best to worst):
-
Functional Cohesion (Ideal): All parts of the module are essential to performing a single, well-defined task. This is the essence of the Single Responsibility Principle (SRP).
- Example: An
EmailValidatorclass with a singlevalidate(emailAddress)method.
- Example: An
-
Sequential Cohesion: The output from one element of the module serves as the input to the next. The elements are dependent in a sequence of operations.
- Example: A
processFilefunction that first reads a file and then parses its content in memory.
- Example: A
-
Communicational Cohesion: Elements all operate on the same set of data. Their actions are distinct but share the same data context.
- Example: A
UserProfileManagerclass that contains methods likeloadProfile(),validateProfileData(), andupdateLastLoginDate(). All operate on a user’s profile data.
- Example: A
-
Procedural Cohesion: Elements are grouped to follow a specific order of execution but have no data link.
- Example: An
OrderProcessormodule that executescheckInventory(),processPayment(), andsendConfirmationEmail()in that specific order.
- Example: An
-
Temporal Cohesion: Elements are grouped because they are executed at the same time (e.g., at system startup or shutdown), without any functional or data relationship.
- Example: An
initializeApplicationmethod that opens a database connection, loads configuration settings, and initializes a logger.
- Example: An
-
Logical Cohesion: Elements perform similar tasks, but the specific task to be executed is selected by a parameter.
- Example: A
processData(dataType)function wheredataTypecan be ‘XML’ or ‘JSON’ to select the action to perform.
- Example: A
-
Coincidental Cohesion (The worst): The elements of the module have absolutely no relationship with each other. They are grouped by chance.
- Example: A
Utilitiesmodule containing functions for date validation, currency conversion, and array sorting.
- Example: A
2. Coupling: The “Interdependence” of Modules
Coupling measures the degree of interdependence between modules. Low coupling is a key goal because it makes modules more independent. A change in a loosely coupled module has little impact on others, which facilitates maintenance, debugging, and evolution.
Coupling Levels (from best to worst):
-
Data Coupling (Ideal): Modules exchange only the necessary data to perform their task, through simple parameters.
- Example: An
OrderServiceclass calling acalculateTax(subtotal, taxRate)method in aTaxCalculatorclass.
- Example: An
-
Stamp Coupling: A module passes an entire data structure (an object) to another module, even if the latter only needs part of it. This creates a dependency on the data structure itself.
- Example:
UserProfileServicecallsupdateAddress(user)where the entireuserobject is passed, but the function only uses the address.
- Example:
-
Control Coupling: A module passes control information (a flag, an enum) to direct the internal logic of the called module. The calling module “knows” how the called module works.
- Example: A
processFile(file, mode)method wheremodedetermines if the file should be read inread-onlyorread-writemode.
- Example: A
-
External Coupling: Modules depend on a common external factor (e.g., a file format, a communication protocol, a shared database).
- Example: Two microservices that both depend on the same version of a database schema.
-
Common Coupling: Modules share a global state, like a global variable. This is extremely dangerous because any module can modify this data, making the system unpredictable.
- Example: Two modules that both read and write to a global
application_statevariable.
- Example: Two modules that both read and write to a global
-
Content Coupling (The worst): A module modifies another module’s internal data (e.g., by directly accessing a private variable). This is a total violation of encapsulation.
- Example: Module A directly modifies a field in Module B without going through a public interface (setter).
3. The Relationship Between the Two: A Key Balance
Cohesion and coupling are inversely related and are two sides of the same architectural coin.
- High Cohesion → Low Coupling: A module with a single, well-defined responsibility (high cohesion, following the SRP) is more autonomous. It needs less information from the outside and interacts with others in a simple, well-defined way, which naturally leads to low coupling.
- Low Cohesion → High Coupling: A module that does many unrelated things (low cohesion) often needs to rely on other modules to perform its various tasks, creating a complex and fragile web of dependencies (high coupling).
Striving for high cohesion and low coupling leads to systems that are maintainable, reusable, and scalable. Principles like SOLID are tools to achieve this. For example, the SRP is a direct path to high cohesion, while the DIP is a powerful technique for achieving low coupling by depending on abstractions instead of concrete implementations. In modern architectures like microservices, these principles are paramount: a well-designed microservice is, by definition, a highly cohesive unit of functionality that is loosely coupled with other services.
Links and Resources
To dive deeper into the concepts of cohesion and coupling in software engineering, here is an updated list of resources.
Articles
-
Coupling and Cohesion - Software Engineering by GeeksforGeeks
This article defines coupling and cohesion, explains their importance, and outlines the different types of each concept.
-
Cohesion and Coupling in Software with Examples by The Valuable Dev
A detailed guide that explores the origin of these concepts, their importance, and how to apply them with practical examples.
Videos
-
SOLID Principles? Nope, just Coupling and Cohesion by CodeOpinion
This video highlights the importance of coupling and cohesion, sometimes even beyond the well-known SOLID principles.
-
Lesson 59 - The Tradeoffs of Loose Coupling by Mark Richards
This video discusses the tradeoffs of loose coupling, using a microservices example to illustrate the challenges of managing errors and data consistency.
-
Coupling and Cohesion Explained by Gui Ferreira
This video provides a clear and concise explanation of these two fundamental software design principles and their importance in creating maintainable code.