Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Coupling (การเชื่อมต่อ) ใน C#: Loose vs Tight Coupling

Coupling (ความเชื่อมต่อ) ใน C# วัดระดับความพึ่งพังระหว่างโมดูลหรือคลาสกัน Coupling ต่ำ (Loose) ดีกว่า Coupling สูง (Tight) เพราะทำให้ระบบยืดหยุ่น ทดสอบง่าย และบำรุงรักษาง่าย

Loose Coupling (การเชื่อมต่อหลวม) - แนะนำ

คลาสไม่พึ่งพารายละเอียดการทำงานของกันและกัน โดยขึ้นอยู่กับ Abstraction (Interface/Abstract Class)

ข้อดี

  • โมดูลหนึ่งเปลี่ยนแปลง ไม่ทำลายโมดูลอื่น
  • เพิ่มความสามารถในการทดสอบ (Testability) - Mock ได้ง่าย
  • โค้ดบำรุงรักษาง่าย
  • ได้รับผลกระทบน้อยจากการเปลี่ยนแปลงของคอมโพเนนต์อื่น

Tight Coupling (การเชื่อมต่อแน่น) - ควรหลีกเลี่ยง

คลาสพึ่งพาการทำงานภายในของกันและกันโดยตรง เช่น new ConcreteClass() ภายในคลาสอื่น

ข้อเสีย

  • ลดความสามารถในการนำกลับมาใช้ใหม่ (Reusability)
  • ยากต่อการทดสอบ Unit Test
  • การเปลี่ยนแปลงคลาสหนึ่ง ส่งผลต่อคลาสอื่นหลายตัว

ตัวอย่างเปรียบเทียบ

Tight Coupling (ไม่ดี)

class EmailService { public void Send(string msg) { ... } }

class OrderProcessor
{
    private EmailService _email = new EmailService(); // ผูกตายกับ Concrete Class
    public void Process() { _email.Send("Order done"); }
}

Loose Coupling (ดี)

interface INotificationService { void Send(string msg); }

class EmailService : INotificationService { ... }
class SmsService : INotificationService { ... }

class OrderProcessor
{
    private readonly INotificationService _notification;
    
    // Dependency Injection
    public OrderProcessor(INotificationService notification)
    {
        _notification = notification;
    }
    
    public void Process() { _notification.Send("Order done"); }
}

หลักการ: "Program to interfaces, not implementations" - เขียนโค้ดต่อ Interface ไม่ใช่ Concrete Class