一个类应该只有一个改变的理由。
定义 - 在这种情况下,责任被认为是改变的一个原因。
该原则指出,如果我们有两个原因要更改某个类,则必须将功能拆分为两个类。每个类仅处理一项职责,如果将来我们需要进行一项更改,我们将在处理它的类中进行更改。当我们需要对具有更多职责的类进行更改时,该更改可能会影响与该类的其他职责相关的其他功能。
示例
代码之前单一职责原则
'using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.Before {
class Program{
public static void SendInvite(string email,string firstName,string lastname){
if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){
throw new Exception("Name is not valid");
}
if (!email.Contains("@") || !email.Contains(".")){
throw new Exception("Email is not Valid!");
}
SmtpClient client = new SmtpClient();
client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"})
}
}
}
遵循单一职责原则编写代码
'using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.After{
internal class Program{
public static void SendInvite(string email, string firstName, string lastname){
UserNameService.Validate(firstName, lastname);
EmailService.validate(email);
SmtpClient client = new SmtpClient();
client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" });
}
}
public static class UserNameService{
public static void Validate(string firstname, string lastName){
if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){
throw new Exception("Name is not valid");
}
}
}
public static class EmailService{
public static void validate(string email){
if (!email.Contains("@") || !email.Contains(".")){
throw new Exception("Email is not Valid!");
}
}
}
}