Single Responsibility Principle (SRP)
This principle states that a class should have only one reason to change, meaning each class should perform a specific function.
Example: Managing user data and sending email notifications.
class UserManager {
constructor() {}
createUser(userData) {
// Logic for creating a user
}
}
class EmailService {
constructor() {}
sendEmail(emailData) {
// Logic for sending an email
}
}
Open/Closed Principle (OCP)
This principle encourages extending functionality by adding new code rather than modifying existing code.
Example: Handling different payment methods in an e-commerce application.
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)
This principle asserts that objects of a derived class should be substitutable for objects of the base class without affecting the correctness of the program.
Example: Managing geometric shapes.
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;
}
}
nterface Segregation Principle (ISP)
This principle advises breaking interfaces into smaller ones to avoid forcing classes to implement methods they don't need.
Example: Interfaces for updating and displaying data.
class UpdateableFeature {
updateFeature() {}
}
class DisplayableFeature {
displayFeature() {}
}
Dependency Inversion Principle (DIP)
This principle suggests that high-level modules should not depend on low-level modules; both should depend on abstractions.
Example: Using dependency injection to manage dependencies.
class OrderProcessor {
constructor(dbConnection, emailService) {
this.dbConnection = dbConnection;
this.emailService = emailService;
}
}
Remember, these examples are just illustrations of how to apply the SOLID principles in Node.js. In practice, you'll need to apply them flexibly based on the purpose and scale of your project.