Single Responsibility Principle(SRP)
Prinsip iki nyatakake yen saben kelas kudu nduweni tanggung jawab siji. Iku nandheske sing kelas kudu nindakake siji fungsi tartamtu lan ora duwe kakehan alasan kanggo ngganti.
Conto: Ngatur informasi pangguna lan ngirim kabar email.
class UserManager {
createUser(userData) {
// Logic for creating a user
}
}
class EmailService {
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() {
// 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)
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() {
// Logic for updating feature
}
}
class DisplayableFeature {
displayFeature() {
// Logic for displaying feature
}
}
Dependency Inversion Principle(DIP)
Prinsip iki nyaranake nggunakake injeksi dependensi kanggo ngatur dependensi.
Conto: Nggunakake injeksi dependensi kanggo ngatur dependensi.
class OrderProcessor {
constructor(dbConnection, emailService) {
this.dbConnection = dbConnection;
this.emailService = emailService;
}
}
Elinga yen ngetrapake SOLID prinsip JavaScript kudu ditindakake kanthi fleksibel adhedhasar tujuan spesifik proyek sampeyan lan pangerten babagan SOLID lan JavaScript.