Single Responsibility Principle (or SRP for short), states that:
A class should have one and only one reason to change, meaning that a class should have only one job.
This doesn't mean that a class should contain only one method or one property, but its members must relate to its responsibility.
For this example, we're going to create an UserService
, its responsibility, is to manage User data in a system.
public class UserService
{
public void CreateUser(string email, string password)
{
if(string.isNullOrEmpty(email)
throw new NullArgumentException("E-mail cannot be null or empty.");
if(string.IsNullOrEmpty(password)
throw new NullArgumentException("Password cannot be null or empty.");
User user = new User(email, password);
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential("email", "password"),
EnableSsl = true,
};
smtpClient.Send("our.app@gmail.com", email, "Welcome!", "Welcome to our system!");
}
}
The example above violates the SRP principle because the CreateUser
method is responsible for two things, creating an user and sending an e-mail.
Let's change it so it respects the SRP principle.
public class UserService
{
private readonly IEmailService _emailService;
public UserService(IEmailService emailService)
{
_emailService = emailService;
}
public void CreateUser(string email, string password)
{
if(string.isNullOrEmpty(email)
throw new NullArgumentException("E-mail cannot be null or empty.");
if(string.IsNullOrEmpty(password)
throw new NullArgumentException("Password cannot be null or empty.");
User user = new User(email, password);
_emailService.SendEmail(email, "Welcome!", "welcome to our system!");
}
}
Now the UserService
is only responsible to create the user, and it delegates the e-mail to another class.
Top comments (0)