Applying the Open-Closed Principle
The open-closed principle is credited to Bertrand Meyer, after its appearance in his 1988 book, Object-Oriented Software Construction (https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction). This book describes the following principles that we can apply to our software:
- A type is open if it can be extended
- A type is closed when it is available to other types
Suppose we have a class called Shape that has a method called area, which in turn calculates the area of the shape. We want to be able to add new shapes to our program without modifying the Shape class, so we make the Shape class open for extension.
To do this, we create a new class called Triangle that inherits from Shape and overrides the area method to calculate the area of a triangle. We can also create a Rectangle class and any other new shapes we want.
Now, whenever we need to calculate the area of a shape, we can simply create a new instance of the...