This is a continuation of the SOLID. In the last post, I covered the S and now we will be continuing with the O. So if you didn't check the last post, feel free to click on the link: https://dev.to/sightlessdog/revisiting-the-s-in-solid-150e
“An entity should be open for extension, but closed for modification”
OO Software Construction
Open for Extension: A module will be said to be open if it is still available for extension.
Closed for modification: This assumes that the module has been given a well-defined, stable description (the interface in the sense of information hiding).
we can achieve that by using a pattern, where high-level modules don't know anything about low-level details. The code is not rigid because nothing would recompile if we add new things, and the code is not fragile because you cannot break the code or let’s say the architecture doesn't let you break things.
Let's use an example for this, everything would be easier to understand.
let's suppose we have a cone class that looks like this
And to make things more complicated, let's say we want to calculate it's volume, then the volume calculator class would look like this
But wait for a second, there's another client who doesn't have a cone but has Cube and wants to calculate the volume.
An approach would be to do the logic in the calculator class
And as you can notice, this class (VolumeCalculator) isn't closed for modification. In order to extend it, we had to change it.
Now using the open/closed principle
We would at first define a high-level module like Shape
And then we would define our concrete shapes separately and by extending the abstract class.
And finally, our Volume Calculator would look like this
And that's how we opened our class for extension by closing it for modification.
Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
Robert C. Martin “Principles of OOD”
Top comments (0)