Open-Closed Principle
“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”
Now this statement is confusing. How entity can be open and closed at same time?
This statement means that we must not edit the main function and it should be adaptable enough to the changes.
For Example, here in below code if we want to add details of few more people we need to add <p> tags for names and departments for those people manually in getDetails() function. In this scenario, we are extending the functionality but along with that we are also editing the main function. Ideally and according to open closed principle we should not edit main function i.e., getDetails() and it should be adaptable enough to show the added person details whenever we want to add more without changing anything in that function.
For that, we can write code in this way. Here we created an array of objects and passed that array as argumrnt to getDetails() function and in getDetails() function we are mapping over the array to get details of passed persons object.
Now here if we want to add show more persons’ details, we just need to add those persons’ object in persons array and result will be get reflected on screen.
As we can see, to extend the main functionality we are no longer editing the getDetails() function. That function is adaptable enough to display the result as par persons array. If we will remove the object from persons array or add few more objects those changes will get reflected without changing the getDetails() function.
By this way, we achieved the open closed principle. Which is considered the most complicated principle in SOLID principles.
And this concludes open-clsoed principle, ‘O’ in ‘SOLID’ principles. Feedback is always appreciated. If you like this article please give a clap and comment your suggestions also. Thank You!!