Sobes.tech
Junior — Middle

How to verify that a class or module adheres to the Single Responsibility Principle?

sobes.tech AI

Answer from AI

The Single Responsibility Principle (SRP) states that a class or module should have only one reason to change, meaning it should be responsible for a single specific task or functionality.

To verify that a class or module adheres to this principle, you can:

  • Look at the number and types of methods: if a class performs too many different functions (for example, working with a database, UI logic, and network requests), it indicates a violation of SRP.
  • Check if parts of the class can be separated into independent modules without losing meaning.
  • Assess whether the class changes for different reasons. If changes occur due to different aspects (for example, changing business logic and changing data storage methods), then the class has multiple responsibilities.

Example:

// Violation of SRP
class UserManager {
    fun saveUserToDb(user: User) { /* save to DB */ }
    fun validateUser(user: User) { /* validation */ }
    fun sendWelcomeEmail(user: User) { /* send email */ }
}

// Correct approach
class UserValidator {
    fun validate(user: User) { /* validation */ }
}

class UserRepository {
    fun save(user: User) { /* save to DB */ }
}

class EmailSender {
    fun sendWelcome(user: User) { /* send email */ }
}

This approach simplifies maintenance and testing of the code.

How to verify that a class or module adheres to the… - sobes.tech