Single Responsibility Principle (SRP) - SOLID
🧱

Single Responsibility Principle (SRP) - SOLID

Tags
Clean Code
Javascript
Software Development
SOLID
Published
Published September 6, 2022
Author
Due Date

The SOLID Principles

SOLID is an acronym for five other class-design principles:
  • Interface Segregation Principle
  • Dependency Inversion Principle.

The Single Responsibility Principle (SRP)

β˜‘οΈ Topic: Objects and Data Structures
Β 
β˜‘οΈ Idea: Each class should have a single responsibility. That means that there should be only one reason to change it. This is one of the SOLID principles.
Β 
β˜‘οΈ Benefits: Maintainability, Reusability
Β 
β˜‘οΈ Guideline: If you can’t say what the class does without using β€œand”, β€œor” , or β€œif” it’s likely doing more than one thing.

Benefits Explained

  • Maintainability: A small class is easy to maintain. Having a single responsibility per class results in small classes.
  • Classes are easier to understand: The smaller the class the fastest one can go through it and understand it.
  • Naming classes: Naming is hard, right? Well if you only have one responsibility you can represent it in the class name. Having more than one responsibility makes it much harder to find a name that represents everything.
Β 

Example

BAD

// BAD class UserSettings { constructor(user) { this.user = user; } changeSettings(settings) { if (this.verifyCredentials()) { // ... } } verifyCredentials() { // ... } }

GOOD

// GOOD class UserAuth { constructor(user) { this.user = user; } verifyCredentials() { // ... } } class UserSettings { constructor(user) { this.user = user; this.auth = new UserAuth(user); } changeSettings(settings) { if (this.auth.verifyCredentials()) { // ... } } }