Junior — Middle
How do you implement the open/closed principle in your projects in practice?
sobes.tech AI
Answer from AI
The Open/Closed Principle means that software entities should be open for extension but closed for modification.
In practice, I implement this principle through:
- Using abstractions (interfaces and abstract classes) to add new implementations without changing existing code.
- Applying design patterns such as Strategy, Decorator, Factory, which allow extending functionality through new classes.
- Avoiding changing already tested and working code; instead, I add new classes or methods.
For example, if I have a payment processing system, I create a PaymentProcessor interface and implement different classes for various payment methods. When adding a new payment method, I simply add a new class without changing existing code:
public interface PaymentProcessor {
void processPayment(double amount);
}
public class CreditCardProcessor implements PaymentProcessor {
public void processPayment(double amount) {
// implementation for credit card
}
}
public class PayPalProcessor implements PaymentProcessor {
public void processPayment(double amount) {
// implementation for PayPal
}
}
Thus, the system is extended without modifying existing classes.