Open/Closed Principle: Write Code That Extends Without Breaking
The Open/Closed Principle (OCP) is a software design rule stating that code components should be open for extension but closed for modification. The goal is to add new behaviors by creating new code rather than editing existing logic, reducing reliance on conditional chains like if-else or switch statements. Achieving this requires strong use of polymorphism and abstraction, allowing new implementations to be plugged in without rewriting what already works. A practical example contrasts a tightly coupled payment processor — modified every time a new method is added — with an interface-based design where each payment type is an isolated class. Reworking old code is costly in time and effort, and repeated changes to finished logic increase the risk of breaking existing features.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in