ชั้นเรียนควรมีเหตุผลเพียงข้อเดียวในการเปลี่ยนแปลง
คำจำกัดความ − ในบริบทนี้ ความรับผิดชอบถือเป็นเหตุผลหนึ่งที่ต้องเปลี่ยนแปลง
หลักการนี้ระบุว่าหากเรามีเหตุผล 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!");
}
}
}
}