Home  >  Article  >  Backend Development  >  How to implement the single responsibility principle using C#?

How to implement the single responsibility principle using C#?

WBOY
WBOYforward
2023-09-12 17:21:02961browse

How to implement the single responsibility principle using C#?

A class should have only one reason to change.

Definition - In this case, responsibility is considered as a reason for the change.

This principle states that if we have two reasons to change a class, we must split the functionality into two classes. Each class handles only one responsibility, and if we need to make a change in the future, we will make it in the class that handles it. When we need to make changes to a class that has more responsibilities, that change may affect other functionality related to other responsibilities of that class.

Example

Single Responsibility Principle before Code

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

Write code following the Single Responsibility Principle

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

The above is the detailed content of How to implement the single responsibility principle using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete