The SOLID Principles - Single Responsibility

The SOLID Principles - Single Responsibility

Exploring the SOLID Principles: Part 1 - Single Responsibility

What does Single Responsibility mean?

The Single Responsibility Principle (SRP) states that a class should have only one responsibility, meaning it should have only one reason to change. In other words, a class should do one thing and do it well, rather than being responsible for multiple tasks or responsibilities. This principle helps to create code that is easier to maintain, test, and reuse, since each class is focused on one specific task.

Here are some examples of how the SRP can be applied in JavaScript:

Example 1: A User Class

Suppose we have a User class that represents a user in a system. The User class has several responsibilities, such as validating user input, handling authentication, and managing user data. However, these responsibilities can be separated into different classes to better follow the SRP.

Here's an example of how we can separate these responsibilities into separate classes:

class UserInputValidator {
  static validateInput(userInput) {
    // Validate user input
  }
}

class UserAuthenticator {
  static authenticateUser(username, password) {
    // Authenticate user
  }
}

class UserDataManager {
  static saveUserData(userData) {
    // Save user data
  }
}

By separating the responsibilities of the User class into separate classes, we can ensure that each class has only one responsibility and is focused on doing one thing well.

Example 2: A Calculator Class

Suppose we have a Calculator class that performs mathematical operations. However, the Calculator class also handles user input and displays the result to the user, which violates the SRP.

Here's an example of how we can separate these responsibilities into separate classes:

class Calculator {
  static add(num1, num2) {
    return num1 + num2;
  }

  static subtract(num1, num2) {
    return num1 - num2;
  }
}

class UserInputHandler {
  static getInput() {
    // Handle user input
  }
}

class ResultDisplayer {
  static displayResult(result) {
    // Display result to user
  }
}

By separating the responsibilities of the Calculator class into separate classes, we can ensure that each class has only one responsibility and is focused on doing one thing well.

In both examples, we can see how following the SRP helps to create code that is easier to maintain, test, and reuse, since each class is focused on one specific task.