High Cohesion
Guidelines for creating components and modules with logically related functionality
personal
## Guidelines for High Cohesion
Cohesion refers to the degree to which elements within a module belong together. High cohesion means that the methods and properties of a class, component, or module are closely related and focused on a single purpose.
1. **Core Principles:**
- Each module, component, or function should have a single, well-defined purpose
- Related functionality should be grouped together
- Unrelated functionality should be separated
- Elements that change together should stay together
- Elements that don't change together should be separated
2. **Signs of Good Cohesion:**
- Clear, focused component and function names that describe a single responsibility
- Methods in a class that operate on the same data
- Functions that work toward a common goal
- Easy-to-write unit tests that don't require excessive mocking
- Components that can be explained in a single sentence
3. **Types of Cohesion (from highest to lowest):**
- **Functional Cohesion:** All elements contribute to a single, well-defined task
- **Sequential Cohesion:** Output from one element serves as input to another
- **Communicational Cohesion:** Elements operate on the same data
- **Procedural Cohesion:** Elements follow a specified sequence of execution
- **Temporal Cohesion:** Elements are related by when they're executed
- **Logical Cohesion:** Elements perform similar functions but are otherwise unrelated
- **Coincidental Cohesion:** Elements have no meaningful relationship (avoid this)
4. **Implementation Strategies:**
- Apply the Single Responsibility Principle
- Create utility modules that focus on specific domains
- Use component composition instead of large monolithic components
- Organize code around business domains or features
- Extract unrelated functionality into separate modules
5. **Benefits of High Cohesion:**
- Improved maintainability and readability
- Better testability
- Easier debugging
- Enhanced reusability
- Simpler code navigation
6. **Practical Applications:**
- Split large files into smaller, more focused ones
- Create helper/utility files organized by domain
- Separate UI, business logic, and data access concerns
- Group related components in directories with clear purposes
- Use hooks to extract and isolate related functionality
By maintaining high cohesion throughout your codebase, you create a more organized, maintainable, and understandable system that's easier to extend and modify over time.