The open closed principle is the O in the SOLID principles. It was created by Bertrand Meyer and states:
Software entities should be open for extension, but closed for modification
Let's dive deeper with an example.
We've been tasked with creating a platform that merges all video streaming sites. The platform will be able to add a platform to its list of platforms, search for a video on all platforms and play a video from the search results. The class can look like so:
CentralVideoStreamingPlatform covers most mainstream video streaming platforms. However, if we were to add another platform, say
#add() would be created. This directly violates the open for extension aspect of OCP.
CentralVideoStreamingPlatform must be open to accept different details without needing to change code that's already written. By overloading
#add() again, we are needlessly changing
CentralVideoStreamingPlatform. Who's to say how many
CentralVideoStreamingPlatform would have as more streaming platforms are added?
CentralVideoStreamingPlatform's extensibility, we can refactor the video streaming classes to implement a
VideoStreamingPlatform interface and use one
The open closed principle is a great principle to keep in mind when writing classes.