Junior — Middle
Can you give an example of how to implement the open/closed principle in practice?
sobes.tech AI
Answer from AI
The Open/Closed Principle states that software entities should be open for extension but closed for modification. In Node.js practice, this can be implemented through the use of abstractions and inheritance or composition.
For example, if you have a class for processing payments and want to add a new payment method without changing existing code, you can create a base class or interface, and implement new payment methods in separate classes:
class PaymentProcessor {
process(payment) {
throw new Error('The process method must be implemented');
}
}
class CreditCardPayment extends PaymentProcessor {
process(payment) {
console.log('Processing credit card payment:', payment);
}
}
class PayPalPayment extends PaymentProcessor {
process(payment) {
console.log('Processing PayPal payment:', payment);
}
}
function handlePayment(processor, payment) {
processor.process(payment);
}
const payment = { amount: 100 };
handlePayment(new CreditCardPayment(), payment);
handlePayment(new PayPalPayment(), payment);
Thus, to add a new payment method, it is enough to create a new class implementing the process method without changing existing code.