如何使用 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("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!");
         }
      }
   }
}

更新於: 05-Dec-2020

298 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.