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 {
createUser(userData) {
// Logic for creating a user
}
}
class EmailService {
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() {
// Common logic for calculating area
}
}
class Rectangle extends Shape {
area() {
// Logic for calculating area of rectangle
}
}
class Square extends Shape {
area() {
// Logic for calculating 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.
class UpdateableFeature {
updateFeature() {
// Logic for updating feature
}
}
class DisplayableFeature {
displayFeature() {
// Logic for displaying feature
}
}
Dependency Inversion Principle(DIP)
Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.
Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.
class OrderProcessor {
constructor(dbConnection, emailService) {
this.dbConnection = dbConnection;
this.emailService = emailService;
}
}
Kumbuka kwamba kutumia SOLID kanuni ndani JavaScript kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na JavaScript.