Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#을 사용하여 단일 책임 원칙을 구현하는 방법은 무엇입니까?

<시간/>

클래스를 변경해야 하는 이유는 단 하나입니다.

정의 − 이러한 맥락에서 책임은 변경해야 하는 한 가지 이유로 간주됩니다.

이 원칙은 클래스를 변경해야 하는 두 가지 이유가 있는 경우 기능을 두 클래스로 분할해야 한다는 것입니다. 각 클래스는 단 하나의 책임만 처리할 것이며 미래에 한 가지 변경을 수행해야 하는 경우 이를 처리하는 클래스에서 변경할 것입니다. 더 많은 책임이 있는 클래스를 변경해야 하는 경우 해당 클래스의 다른 책임과 관련된 다른 기능에 영향을 미칠 수 있습니다.

예시

단일 책임 원칙 이전의 강령

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!");
         }
      }
   }
}