The Open/Closed Principle (OCP) states:
Code should be open for extension but closed for modification.
This means you should be able to add new functionality without changing existing code.
The PaymentService uses multiple if-else or switch statements to process different payment methods.
if (paymentType.equals("CARD")) {
...
} else if (paymentType.equals("UPI")) {
...
} else if (paymentType.equals("PAYPAL")) {
...
}Whenever a new payment method is added, the existing class must be modified.
Each payment method has its own implementation.
Payment→ InterfaceCardPayment→ Processes Card paymentsUpiPayment→ Processes UPI paymentsPaypalPayment→ Processes PayPal payments
To add a new payment method (e.g., CryptoPayment), simply create a new class that implements the PaymentService interface.
No existing code needs to be changed.
b_OCP
│
├── before/
│ └── OCP Violation
│
├── after/
│ └── OCP Implementation
│
└── README.md
- Easy to add new features
- Reduces modification of existing code
- Improves maintainability
- Supports scalability
- Encourages the use of polymorphism
Think of an online payment gateway.
Initially, it supports:
- 💳 Card Payment
Later, the company wants to add:
- 📱 UPI Payment
🅿️ PayPal- 💰 Crypto Payment
Instead of modifying the existing payment logic every time, simply create a new payment class for each new payment method.
Extend the system by adding new classes, not by modifying existing ones.