SOLID is an acronym and stands for 5 important object oriented principles which help to create good software architecture.
- S stands for SRP (Single responsibility principle)
- O stands for OCP (Open closed principle)
- L stands for LSP (Liskov substitution principle)
- I stands for ISP ( Interface segregation principle)
- D stands for DIP ( Dependency inversion principle)
So let’s start understanding each principle with simple c# examples.
SRP (Single responsibility principle)
“There should never be more than one reason for a class to change”
The SRP (Single responsibility principle) says a class should focus on doing one thing, or have one responsibility. This doesn’t mean it should only have one method, but instead all the methods should relate to a single purpose.
class Users
{
public void RegisterUser(User user)
{
try
{
user.Insert();
if(ValidateEmail(user.Email))
SendEmail(new MailMessage("User Registered!", user.Email)))
}
catch (Exception ex)
{
File.WriteAllText(@"C:\Error.txt", ex.ToString());
}
}
public bool ValidateEmail(string email)
{
return email.Contains("@");
}
public SendEmail(MailMessage message)
{
_smtpClient.Send(message);
}
}
The above Users class is doing things WHICH HE IS NOT SUPPOSED TO DO. Users class should do user datavalidations, call the user data access layer etc , but if you see closely it also doing EMAIL activity. In simple words its over loaded with lot of responsibility.
So SRP says that a class should have only one responsibility and not multiple.So if we apply SRP we can move that EMAIL activity to some other class who will only look after EMAIL activities.
class Users
{
EmailService _emailService;
public void RegisterUser(User user)
{
try
{
user.Insert();
if(_emailService.ValidateEmail(user.Email))
_emailService.SendEmail(new MailMessage("User Registered!", user.Email)))
}
catch (Exception ex)
{
//DO NOTHING
}
}
class EmailService
{
public bool ValidateEmail(string email)
{
return email.Contains("@");
}
public SendEmail(MailMessage message)
{
_smtpClient.Send(message);
}
}