Naomi Dennis
Posted on November 26, 2019
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 DisneyPlus
, another #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 #add()
CentralVideoStreamingPlatform
would have as more streaming platforms are added?
To ensure CentralVideoStreamingPlatform
's extensibility, we can refactor the video streaming classes to implement a VideoStreamingPlatform
interface and use one #add()
.
In Conclusion
The open closed principle is a great principle to keep in mind when writing classes.
Posted on November 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.