Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Open/Closed Principle (OCP)

📖 What is OCP?

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.


❌ Before (OCP Violation)

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.


✅ After (OCP Followed)

Each payment method has its own implementation.

  • Payment → Interface
  • CardPayment → Processes Card payments
  • UpiPayment → Processes UPI payments
  • PaypalPayment → 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.


📂 Project Structure

b_OCP
│
├── before/
│   └── OCP Violation
│
├── after/
│   └── OCP Implementation
│
└── README.md

🎯 Benefits of OCP

  • Easy to add new features
  • Reduces modification of existing code
  • Improves maintainability
  • Supports scalability
  • Encourages the use of polymorphism

💡 Real-World Example

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.


🚀 Key Takeaway

Extend the system by adding new classes, not by modifying existing ones.