Article
Open-Closed Principle: Extending Without Modifying
Software entities should be open for extension but closed for modification. Here's why that matters.
The Open-Closed Principle (OCP) states that you should be able to add new functionality to a software component without changing its existing source code.
The Problem with Modification
Every time you modify existing, working code, you risk introducing bugs. In large systems, this leads to a 'house of cards' effect where a change in one place causes a collapse in another.
Achieving OCP through Abstraction
The key to OCP is using interfaces or abstract classes. Instead of writing code that depends on a specific implementation, write code that depends on an abstraction.
Example: Payment Processing
If your system handles credit cards and you want to add PayPal support, don't add an if (type == PAYPAL) block to your existing payment processor. Instead, create a PaymentStrategy interface and implement it for both CreditCard and PayPal.
By doing this, your core processing logic remains untouched (closed for modification) while remaining open to any number of new payment methods (open for extension).
Recommended by our partners
Discussion
Keep the conversation going
Log in to join the discussion.
No comments yet. The first thoughtful reply can set the tone for the whole thread.