Kutumia SOLID Kanuni katika C#: Mifano na Mbinu Bora

Single Responsibility Principle(SRP)

Kanuni hii inasema kwamba kila darasa linapaswa kuwa na jukumu moja. Inasisitiza kwamba darasa linapaswa kufanya kazi moja maalum na lisiwe na sababu nyingi za kubadilika.

Mfano: Kusimamia maelezo ya mtumiaji na kutuma arifa za barua pepe.

class UserManager {  
  public void CreateUser(UserData userData) {  
    // Logic to create a user  
  }  
}  
  
class EmailService {  
  public void SendEmail(EmailData emailData) {  
    // Logic to send an email  
  }  
}  

Open/Closed Principle(OCP)

Kanuni hii inahimiza kupanua utendakazi kwa kuongeza msimbo mpya badala ya kurekebisha msimbo uliopo.

Mfano: Kushughulikia mbinu tofauti za malipo katika programu ya biashara ya mtandaoni.

abstract class PaymentProcessor {  
  public abstract void ProcessPayment();  
}  
  
class CreditCardPaymentProcessor: PaymentProcessor {  
  public override void ProcessPayment() {  
    // Logic to process credit card payment  
  }  
}  
  
class PayPalPaymentProcessor: PaymentProcessor {  
  public override void ProcessPayment() {  
    // Logic to process PayPal payment  
  }  
}  

Liskov Substitution Principle(LSP)

Kanuni hii inadai kuwa vipengee vya darasa linalotokana vinapaswa kubadilishwa kwa vitu vya darasa la msingi bila kuathiri usahihi wa programu.

Mfano: Kusimamia maumbo ya kijiometri.

abstract class Shape {  
  public abstract double CalculateArea();  
}  
  
class Rectangle: Shape {  
  public override double CalculateArea() {  
    // Logic to calculate area of rectangle  
  }  
}  
  
class Square: Shape {  
  public override double CalculateArea() {  
    // Logic to calculate area of square  
  }  
}  

Interface Segregation Principle(ISP)

Kanuni hii inashauri kuvunja miingiliano kuwa ndogo ili kuzuia kulazimisha madarasa kutekeleza njia ambazo hazihitaji.

Mfano: Violesura vya kusasisha na kuonyesha data.

interface IUpdateableFeature {  
  void UpdateFeature();  
}  
  
interface IDisplayableFeature {  
  void DisplayFeature();  
}  

Dependency Inversion Principle(DIP)

Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.

Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.

class OrderProcessor {  
  private readonly DBConnection _dbConnection;  
  private readonly EmailService _emailService;  
  
  public OrderProcessor(DBConnection dbConnection, EmailService emailService) {  
    _dbConnection = dbConnection;  
    _emailService = emailService;  
  }  
}  

Kumbuka kwamba kutumia SOLID kanuni katika C# kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na C#.