Single Responsibility Principle
- A class should have one, and only one, reason to change.
- This means that a class must have only one responsibility.
Example 1
Problem
public class Order
{
public int OrderId { get; set; }
public string Customer { get; set; }
public decimal OrderAmount { get; set; }
}
public class OrderService
{
AppDbContext context;
public void OrderService(AppDbContext context)
{
this.context = context;
}
public void CreateOrder(Order order)
{
//logging
Console.WriteLine("CreateOrder start");
//Save Order
context.Orders.Add(order);
context.SaveChanges();
//Send Email
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info@MyWebsiteDomainName.com", "myIDPassword");
MailMessage mail = new MailMessage();
mail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress(order.Customer));
mail.Subject = "New Order";
mail.Body = "Thank you for your order";
smtpClient.Send(mail);
Console.WriteLine("CreateOrder end");
}
}
- Order class has the implementation detail of
- how to send email.
- how to log.
- If logging or send email changes, the order class should be updated.
Solution
Logger
class is responsible for logging activity
OrderRepository
is responsible for saving order
EmailManager
is responsible for sending email
public class Order
{
public int OrderId { get; set; }
public string Customer { get; set; }
public decimal OrderAmount { get; set; }
}
public class OrderService
{
IOrderRepository orderRepo;
I ILogger logger;
IEmailManager emailManager;
public void OrderService(IOrderRepository orderRepo, ILogger logger, IEmailManager emailManager)
{
this.orderRepo = orderRepo;
this.logger = logger;
this.EmailManager = emailManager;
}
public void CreateOrder(Order order)
{
logger.Write("CreateOrder start");
//Save Order
orderRepo.CreateOrder(order);
//Send Email
emailManager.Send(order.Customer, "New Order", "Thank you for your order")
logger.Write("CreateOrder end");
}
}
Example 2
Problem
public class UserManager
{
public bool AuthenticateUser(string username, string password)
{
Console.WriteLine("Authenticate user");
return true;
}
public void UpdateUserProfile(string userid, string address)
{
Console.WriteLine("Update User");
}
public void SendEmail(string email, string message)
{
Console.WriteLine("Email user");
}
}
Solution
public class UserAuthenticator
{
public bool AuthenticateUser(string username, string password)
{
Console.WriteLine("Authenticate user");
return true;
}
}
public class UserProfileManager
{
public void UpdateUserProfile(string userid, string address)
{
Console.WriteLine("Update User");
}
}
public class EmailNotifier
{
public void SendEmail(string email, string message)
{
Console.WriteLine("Email user");
}
}