Single Responsibility Principle

The Single Responsibility Principle means a class should only have one reason to change—basically, it should focus on a single responsibility. This makes the code easier to maintain, test, and extend.

SRP violation example

Let’s say we are building a to-do application. And we are working on our Task class, and we create something like this:

class Task {
  constructor(title, priority) {
    this.title = title;
    this.priority = priority;
  }

  generateReport() {...}

  log() {...}
}

This violates SRP because Task has extra responsibilities.

Bad SRP

If we need to make changes in task creation, report generator, or logging, the Task class would need to be modified, leading to tightly coupled code and potential maintenance issues.

A better approach

To follow SRP, we can reorganize our code like this:

class Task {
  constructor(title, priority) {
    this.title = title;
    this.priority = priority;
  }
}

class Report {
  generateReport() {...}
}

class Logger {
  log() {...}
}

Yes, we introduced new classes, but now everything has only one responsibility. Task class is responsible for everything related to tasks, Report is responsible for generating reports, and Logger is responsible for logging.

Good SRP

This looks like a small change, but trust me, it makes a huge difference in bigger projects. By keeping things separated, you’ll find it much easier to maintain and extend your code in the long run.


Find this post helpful? Subscribe and get notified when I post something new!