Open-Closed Principle (OCP)
The Open-Closed Principle states that classes should be open to extension, but closed to modification.
Changes to a program should occur primarily by writing new code, not changing code that already exists.
Example
- What if we wanted our
Hero
to use a different type of weapon?Bow
orMagicWand
? - Requires us changing all the places we referenced the
Sword
class - lots of modifications, not much extension.
Fix is to use Strategy Pattern:
The Open-Closed Principle is closely related to the concept of Inheritance and Virtual Functions.
For example:
This function is open to extension: we can add more functionality by defining new types of Book
s, and closed to modification: countHeavy
never needs to change now that it has been written.
Compare this to WhatIsIt
(see dynamic_cast)
- not open to extension: cannot get new behavior without modifying the source code
- not closed to modification either
OCP is an Ideal
Open/closed principle is an ideal - writing a program will require modifications at some point.
Plan for things that are most likely to change, account for those.