Cohesion and coupling are core metrics for modularity across services and codebases. Aim for high cohesion within services and loose coupling between them.
1. Cohesion (Internal Strength)
Definition: Cohesion measures how strongly related and focused the responsibilities of a module/class/service are.
A. High Cohesion (Good)
- Characteristics: Service focuses on a single business capability; all elements support that capability.
- Benefits: Understandability, Testability, Change Isolation.
B. Low Cohesion (Bad)
- Characteristics: Bundles unrelated functionalities ("God Service").
- Consequences: Changes in one area can break others.
C. Principle: Domain-Driven Design (DDD)
Align services with Bounded Contexts to achieve high cohesion. A term like “Customer” has one specific meaning per context.
2. Coupling (External Dependency)
Definition: Coupling measures the degree of interdependence between modules/services.
A. Loose Coupling (Good)
- Characteristics: Changes in one service minimally impact others; stable contracts.
- Benefits: Independent Deployment, Resilience, Technology Freedom.
B. Tight Coupling (Bad)
- Characteristics: Relies on internal details of another service.
- Examples: Shared databases, non-versioned APIs, shared business-logic libraries.
C. Types of Coupling in Distributed Systems
| Coupling Type | Description | Recommendation |
|---|---|---|
| Temporal Coupling | Two actions must happen together in time (e.g., synchronous HTTP request). | Avoid; prefer asynchronous messaging and eventual consistency. |
| Data Coupling | Dependencies on data format (API schema, event contracts). | Use strict versioning and schemas (e.g., Avro) for evolution. |
| Content/Pathological Coupling | One service modifies internal data structures of another (shared DB). | Forbidden — destroys independence. |
3. The Coupling/Cohesion Goal
Goal: High Cohesion and Loose Coupling.
| Factor | Low Coupling | High Cohesion |
|---|---|---|
| Analogy | Minimal dependencies on other groups. | All members work toward a unified goal. |
| Impact | Independent changes and resilience. | Easy to understand and test. |
| Achieved via | Strict contracts, async communication, independent databases. | DDD bounded contexts, SRP adherence. |
Coupling vs Cohesion by Architecture Style
Relative scores (1–5) for Coupling (lower is better) and Cohesion (higher is better).