Tip #27: The Open–Closed Principle (OCP)
Word to remember: abstraction
Definition: Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Since 1988, when Bertrand Meyer introduced this principle, it has been closely tied to object-oriented programming (OOP). When implemented correctly, OCP helps achieve flexibility, reusability, extensibility, and maintainability—all of which are crucial for scalable software systems.
Remember OOP principles?
All right! How to do it?
public interface Payment {
void processPayment(double amount);
}
public class CreditCardPayment implements Payment {
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
public class PayPalPayment implements Payment {
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
To introduce a new payment method, it’s straightforward: Add a new class, implement the Payment
interface: No need to modify the existing code - OCP ✅ !
Dependency Injection is a good example too, right?
We may now have a service that uses Payment
interface, and we can switch the payment method without change service code.
@Service
public class PaymentService {
private final Payment payment;
public PaymentService(Payment payment) {
this.payment = payment;
}
public void makePayment(double amount) {
payment.processPayment(amount);
}
}
When to avoid?
I posted an example earlier that doesn’t violate OCP, but it illustrates the potential issue of having too many abstractions. While abstraction is powerful, overdoing it can lead to unnecessary complexity.
It’s important to strike a balance between abstraction and simplicity. In fact, Robert Martin wrote: Resisting premature abstraction is as important as abstraction itself.
See you tomorrow.
Happy coding!