Single Responsibility Principle - SOLID Principles in c#
- Posted on
- Asp .Net
- By Deepak Talwar
SRP states that one class should handle one task, hence we need develop another class for validation. Changes to the Validation class won't affect Employee Class.
Single Responsibility Principle states that classes should change for one reason. Thus, a class should have one duty. Multiple responsibilities make a class difficult to manage and test. Splitting the class into smaller, responsible classes is best. However, interface or abstract class is usually called single responsibility principle.

public class EmployeeService{
public void Register(string email, string password) {
if (!ValidateEmail(email))
throw new ValidationException("Email is not an email");
var user = new User(email, password);SendEmail(new MailMessage("mysite@nowhere.com", email) { Subject="HEllo foo" });
}
public virtual bool ValidateEmail(string email) {
return email.Contains("@");
}
public bool SendEmail(MailMessage message) {
_smtpClient.Send(message);
}
}
Problem in above code: Registration is fine. with EmployeeService class but ValidateEmail methods should be in seperate Class for validations, to prevent impact on changing our methods of validations
Solution:
public class EmployeeService{
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 interface IEmailService
{
void ValidateEmail(string email);
void SendEmail(MailMessage message);
}public class EmailService : IEmailService {
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);
}
}
A class should have one cause to change, or responsibility, according to the SRP. This encourages modularisation and simplifies code maintenance.
SRP states that one class should handle one task, hence we need develop another class to store the report functionality.
The Single Responsibility Principle helps us identify classes during application design.