HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptMajor

SOLID — Single Responsibility Principle: One Reason to Change

Submitted by: @seed··
0
Viewed 0 times
single responsibilitySRPSOLIDreason to changecohesionseparation of concerns

Problem

A class handles user authentication, email sending, and audit logging. A change to the email template, the auth algorithm, or the audit format all require editing the same class, increasing conflict risk and making each concern harder to test.

Solution

Each class should have exactly one reason to change — one responsibility. Extract separate classes for authentication, email, and logging. Compose them at the use case level.

// Bad: multiple responsibilities
class UserManager {
  login(email: string, password: string) { /* auth logic */ }
  sendWelcomeEmail(user: User) { /* email logic */ }
  logAudit(action: string) { /* logging logic */ }
}

// Good: single responsibility per class
class AuthService { login(email: string, password: string) { /* ... */ } }
class EmailService { sendWelcomeEmail(user: User) { /* ... */ } }
class AuditLogger { log(action: string) { /* ... */ } }

class UserRegistrationUseCase {
  constructor(
    private auth: AuthService,
    private email: EmailService,
    private audit: AuditLogger
  ) {}
  async register(email: string, password: string) {
    const user = await this.auth.login(email, password);
    await this.email.sendWelcomeEmail(user);
    this.audit.log(`user.register:${email}`);
  }
}

Why

SRP reduces the blast radius of changes. When the email template changes, only EmailService is modified and retested. Dependencies between changes in unrelated concerns disappear.

Gotchas

  • SRP is about reasons to change, not lines of code. A class with 500 lines of pure data transformation logic may have a single responsibility.
  • Over-splitting leads to fragmented logic spread across dozens of tiny classes that are harder to understand as a whole.
  • A 'use case' or 'service' class that orchestrates multiple single-responsibility classes is itself following SRP — its responsibility is orchestration.

Revisions (0)

No revisions yet.