SOLID & Design Patterns Interview Question #14

What is cohesion in software design?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

Cohesion describes how closely related the responsibilities inside a module are. High cohesion means a class or component contains behavior that naturally belongs together.

Detailed Explanation

Cohesion describes how closely related the responsibilities inside a module are. High cohesion means a class or component contains behavior that naturally belongs together.

High cohesion generally improves readability and maintainability. A class that mixes authentication, reporting, file conversion, and billing logic has low cohesion even if each individual method works correctly.

Code Example

public class PasswordHasher
{
    public string Hash(string password) => "...";
    public bool Verify(string password, string hash) => true;
}

// Both operations belong to password hashing.