Single Responsibility Principle (SRP):
As per the concepts of the Single Responsibility Principle, every module of the software must have only a single reason to change. Everything in that particular class
This means, that every single class or class-like structure in our code must have only one job to perform. All the things in that class must be related to one single purpose. Our class must not be multifunctional at all.
The Single Responsibility Principle represents a way of recognizing classes at the Appās design phase making you think of all the ways a class can change. When you see an excellent clarity of operation requests, a fine separation of responsibilities occurs.
Let us comprehend this with an example.
Ā
public class UserService
{
EmailService _emailService;
DbContext _dbContext;
public UserService(EmailService aEmailService, DbContext aDbContext)
{
_emailService = aEmailService;
_dbContext = aDbContext;
}
public void Register(string email, string password)
{
if (!_emailService.ValidateEmail(email))
throw new ValidationException("Email is not an email");
var user = new User(email, password);
_dbContext.Save(user);
emailService.SendEmail(new MailMessage("myname@mydomain.com", email) {Subject="Hi. How are you!"});
}
}
public class EmailService
{
SmtpClient _smtpClient;
public EmailService(SmtpClient aSmtpClient)
{
_smtpClient = aSmtpClient;
}
public bool virtual ValidateEmail(string email)
{
return email.Contains("@");
}
public bool SendEmail(MailMessage message)
{
_smtpClient.Send(message);
}
}