What is highcohesion?
High cohesion refers to a design principle where the elements inside a single module, class, or component are closely related and work together to achieve a single, well‑defined purpose. In other words, everything inside that unit belongs together because it contributes to the same responsibility.
Let's break it down
Think of a toolbox. If you put only screwdrivers in one drawer and only hammers in another, each drawer has a clear job - that’s high cohesion. In code, a class that only handles user authentication (login, logout, password reset) is highly cohesive, while a class that mixes authentication, file I/O, and UI rendering is low cohesion.
Why does it matter?
- Easier to understand: When a component does one thing, newcomers can grasp its role quickly.
- Simpler to maintain: Changes affect fewer places because responsibilities aren’t tangled.
- Better testability: You can write focused unit tests for a single purpose.
- Improved reusability: A cohesive piece can be moved or reused without dragging unrelated code.
Where is it used?
High cohesion is a goal in many areas of software engineering:
- Object‑oriented programming (classes and methods)
- Functional programming (pure functions with a single responsibility)
- Microservice architecture (each service handles one business capability)
- API design (endpoints that perform one clear action)
- Component‑based UI frameworks (widgets that manage a specific UI piece)
Good things about it
- Leads to cleaner, more readable code.
- Reduces the risk of bugs when modifying or extending functionality.
- Makes parallel development easier because teams can work on separate, well‑defined units.
- Facilitates scaling: you can replace or scale a cohesive component without affecting others.
Not-so-good things
- Over‑splitting can create too many tiny components, increasing the overhead of wiring them together.
- Striving for perfect cohesion may lead to excessive abstraction, making the system harder to navigate.
- In some cases, a little related functionality is more practical to keep together; forcing strict separation can add unnecessary complexity.