>  기사  >  백엔드 개발  >  C#을 사용하여 단일 책임 원칙을 구현하는 방법은 무엇입니까?

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

WBOY
WBOY앞으로
2023-09-12 17:21:02961검색

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

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

Definition - 이 경우 책임이 변경 사유로 간주됩니다.

이 원칙은 클래스를 변경해야 하는 두 가지 이유가 있는 경우 기능을 두 클래스로 분할해야 한다고 명시합니다. 각 클래스는 하나의 책임만 처리하며, 향후 변경이 필요한 경우 이를 처리하는 클래스에서 변경하도록 하겠습니다. 더 많은 책임이 있는 클래스를 변경해야 하는 경우 해당 변경 사항은 해당 클래스의 다른 책임과 관련된 다른 기능에 영향을 미칠 수 있습니다.

코드 이전의 단일 책임 원칙

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

위 내용은 C#을 사용하여 단일 책임 원칙을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제