Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#으로 배우는 단일 책임 원칙(SRP): SOLID 설계의 첫걸음

단일 책임 원칙(Single Responsibility Principle, SRP)은 SOLID 객체지향 설계 원칙 중 하나로, '클래스는 변경될 이유가 오직 하나만 있어야 한다'는 핵심 개념을 담고 있습니다.

정의

여기서 말하는 책임(Responsibility)은 곧 변경될 이유(Reason to Change)를 의미합니다. 즉, 하나의 클래스가 두 가지 이상의 변경 이유를 가진다면, 그 기능을 서로 다른 두 개의 클래스로 분리해야 한다는 것입니다.

각 클래스는 하나의 책임만 담당하므로, 나중에 수정이 필요할 때 해당 기능을 처리하는 클래스만 변경하면 됩니다. 반면 여러 책임을 한꺼번에 가진 클래스를 수정하면, 다른 책임과 관련된 기능까지 예기치 않게 영향을 받아 버그나 부작용이 발생할 위험이 커집니다.

이러한 원칙을 지키면 코드의 응집도는 높아지고 결합도는 낮아져, 테스트와 유지보수가 훨씬 쉬워집니다.

예제

1. 단일 책임 원칙 적용 전 코드

아래 코드에서는 이름 검증, 이메일 검증, 메일 발송이라는 세 가지 책임이 하나의 메서드에 모두 포함되어 있습니다.

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

2. 단일 책임 원칙 적용 후 코드

검증 로직을 각각 별도의 클래스(UserNameService, EmailService)로 분리하여, 각 클래스가 하나의 책임만 갖도록 리팩토링했습니다.

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

마무리

위 예제처럼 단일 책임 원칙을 적용하면 각 클래스의 역할이 명확해지고, 특정 기능의 변경이 다른 기능에 미치는 영향을 최소화할 수 있습니다. 결과적으로 더 안정적이고 확장 가능한 소프트웨어를 만들 수 있습니다.