Utumiaji wa SOLID Kanuni katika Node.js

Single Responsibility Principle(SRP)

Kanuni hii inasema kwamba darasa linapaswa kuwa na sababu moja tu ya kubadilika, ikimaanisha kuwa kila darasa linapaswa kufanya kazi maalum.

Mfano: Kudhibiti data ya mtumiaji na kutuma email arifa.

class UserManager {  
  constructor() {}  
    
  createUser(userData) {  
    // Logic for creating a user  
  }  
}  
  
class EmailService {  
  constructor() {}  
    
  sendEmail(emailData) {  
    // Logic for sending 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.

class PaymentProcessor {  
  processPayment() {  
    // Common logic for payment processing  
  }  
}  
  
class CreditCardPaymentProcessor extends PaymentProcessor {  
  processPayment() {  
    // Logic for processing credit card payment  
  }  
}  
  
class PayPalPaymentProcessor extends PaymentProcessor {  
  processPayment() {  
    // Logic for processing 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.

class Shape {  
  area() {}  
}  
  
class Rectangle extends Shape {  
  constructor(width, height) {}  
    
  area() {  
    return this.width * this.height;  
  }  
}  
  
class Square extends Shape {  
  constructor(side) {}  
    
  area() {  
    return this.side * this.side;  
  }  
}  

Kanuni ya Utengano wa kiolesura(ISP)

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

Mfano: Violesura vya kusasisha na kuonyesha data.

class UpdateableFeature {  
  updateFeature() {}  
}  
  
class DisplayableFeature {  
  displayFeature() {}  
}  

Dependency Inversion Principle(DIP)

Kanuni hii inaonyesha kuwa moduli za kiwango cha juu hazipaswi kutegemea moduli za kiwango cha chini; zote mbili zinapaswa kutegemea vifupisho.

Mfano: Kutumia dependency injection kudhibiti utegemezi.

class OrderProcessor {  
  constructor(dbConnection, emailService) {  
    this.dbConnection = dbConnection;  
    this.emailService = emailService;  
  }  
}  

Kumbuka, mifano hii ni vielelezo tu vya jinsi ya kutumia SOLID kanuni katika Node.js. Kwa vitendo, utahitaji kuzitumia kwa urahisi kulingana na madhumuni na ukubwa wa mradi wako.