Single Responsibility Principle(SRP)
Prinsip iki nyatakake yen kelas kudu mung siji alasan kanggo ngganti, tegese saben kelas kudu nindakake fungsi tartamtu.
Conto: Ngatur data pangguna lan ngirim email kabar.
class UserManager {
constructor() {}
createUser(userData) {
// Logic for creating a user
}
}
class EmailService {
constructor() {}
sendEmail(emailData) {
// Logic for sending an email
}
}
Open/Closed Principle(OCP)
Prinsip iki nyengkuyung nambah fungsi kanthi nambah kode anyar tinimbang ngowahi kode sing wis ana.
Conto: Nangani macem-macem cara pembayaran ing aplikasi e-commerce.
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)
Prinsip iki negesake manawa obyek saka kelas asale kudu bisa diganti kanggo obyek kelas dasar tanpa mengaruhi akurasi program kasebut.
Tuladha: Ngatur wangun geometris.
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;
}
}
Prinsip Segregasi Antarmuka(ISP)
Prinsip iki menehi saran supaya antarmuka rusak dadi luwih cilik supaya ora meksa kelas kanggo ngetrapake metode sing ora dibutuhake.
Conto: Antarmuka kanggo nganyari lan nampilake data.
class UpdateableFeature {
updateFeature() {}
}
class DisplayableFeature {
displayFeature() {}
}
Dependency Inversion Principle(DIP)
Prinsip iki nyaranake yen modul tingkat dhuwur ora kudu gumantung marang modul tingkat rendah; loro kudu gumantung ing abstraksi.
Conto: Nggunakake dependency injection kanggo ngatur dependensi.
class OrderProcessor {
constructor(dbConnection, emailService) {
this.dbConnection = dbConnection;
this.emailService = emailService;
}
}
Elinga, conto iki mung ilustrasi babagan carane ngetrapake SOLID prinsip ing Node.js. Ing praktik, sampeyan kudu ngetrapake kanthi fleksibel adhedhasar tujuan lan skala proyek sampeyan.