Skip to main content

The Single Responsibility Principle (SRP)

The Single Responsibility Principle (SRP) is a principle of object-oriented programming (OOP) that states that a class should only have a single responsibility, or a single reason to change. In other words, a class should focus on one specific aspect of the problem domain, and should not be cluttered with unrelated responsibilities or functionality.

Explain The Single Responsibility Principle like I'm five

The Single Responsibility Principle is like a job. Everyone has a different job, and they do their job really well. For example, one person might be really good at making cookies, and another person might be really good at washing dishes. If they each just do their own job, then they will be able to make lots of cookies and wash lots of dishes. But if they try to do each other's job, then they might not be as good at it, and they might not be able to make as many cookies or wash as many dishes. So it's better for everyone to just do their own job and not try to do other people's jobs.

Code examples

In this code, the User class is responsible for multiple things: validating input, saving to the database, and sending an email. This violates the Single Responsibility Principle because the class has more than one reason to change. For example, if the way that the input is validated needs to change, or if the way that the welcome email is formatted needs to change, the User class would need to be modified.

class User
def initialize(name, email, password)
@name = name
@email = email
@password = password
end

def register
# Validate input
if @name.empty? || @email.empty? || @password.empty?
return "Invalid input"
end

# Save user to database
db = Database.new
db.save(@name, @email, @password)

# Send welcome email
Mailer.send_welcome_email(@email)
end
end