Remember fullform - Open for Extension and closed for modification.
The Open/Closed Principle means that once you've built something in your code, it should stay as it is and not be changed. You can add new features or functions without altering the existing stuff.
Let's use an example involving a payment system and walk through it step by step to explain the Open/Closed Principle (OCP) with Java code.
Step 1: Create a Payment System (Initial Design):
Imagine you have a payment system that processes payments through different payment methods. You initially design the system with classes for credit card and PayPal payments:
class PaymentProcessor {
public void processCreditCardPayment(CreditCardPayment payment) {
// Process credit card payment
}
public void processPayPalPayment(PayPalPayment payment) {
// Process PayPal payment
}
}
class CreditCardPayment {
// Credit card payment details
}
class PayPalPayment {
// PayPal payment details
}
Step 2: Identify the Problem:
The problem is that if you want to add a new payment method (e.g., a "BitcoinPayment" method), you'd have to modify the existing PaymentProcessor
class, which violates the Open/Closed Principle. This is not ideal because it means changing working code, which can introduce errors and makes the system less maintainable.
Step 3: Create an Interface and an Extension Mechanism (Solution):
- Create an interface called
PaymentMethod
that defines aprocessPayment
method, which all payment methods must implement. This abstracts the common behavior required of any payment method. - Modify the
PaymentProcessor
to accept an object of typePaymentMethod
and call theprocessPayment
method on it. Now, thePaymentProcessor
is open for extension and can work with any class that implements thePaymentMethod
interface.
interface PaymentMethod {
void processPayment();
}
class PaymentProcessor {
public void processPayment(PaymentMethod payment) {
payment.processPayment();
}
}
class CreditCardPayment implements PaymentMethod {
@Override
public void processPayment() {
// Process credit card payment
}
}
class PayPalPayment implements PaymentMethod {
@Override
public void processPayment() {
// Process PayPal payment
}
}
Step 4: Benefits of the Solution:
The solution allows you to easily add new payment methods (e.g., BitcoinPayment
) by creating a new class that implements the PaymentMethod
interface. You no longer need to change the existing PaymentProcessor
or other payment method classes, ensuring that the software follows the Open/Closed Principle. This makes your code more flexible, maintainable, and less prone to errors when adding new features.
"Your feedback and ideas are invaluable β drop a comment, and let's make this even better!"
π If you enjoy the content, please π like, π share, and π£ follow for more updates!
Join me on a professional journey through my LinkedIn profile: Linkedin Profile
Top comments (0)