如何使用 C# 实现单一职责原则?
一个类应该只存在一个改变原因。
定义 − 在此上下文中,责任被认为是一个改变原因。
这一原则指出,如果我们为一个类有 2 个改变原因,我们必须将该功能分成两个类。每个类将只处理一种责任,如果在未来我们需要进行一项更改,我们将在处理该更改的类中进行更改。当我们需要在一个肩负更多责任的类中进行更改时,该更改可能会影响该类其他责任相关的其他功能。
示例
单一职责原则之前的代码
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("[email protected]", 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("[email protected]", 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!"); } } } }
广告