The Open/Closed Principle is one of the SOLID principles of object-oriented design, and it states that a software entities(classes, functions, modules) should be open for extension but closed for modification.
Open for Extension: You can add new features or behaviors without changing the existing code.
Closed for Modification: You don't need to go back and mess with the original code; you can build on top of it.
First we will look at an example where open/closed principle is violated in a React component and how we can refactor it to adhere to this principle.
Suppose you have a Notification
component that displays different types of notifications, such as success, error, info messages-
Now, imagine the UX team comes up with design modification that the success notification will have a close icon, error notification will have a Try Again button when needed at the bottom, info notification will have a tooltip with icon and so on.
If you want to code these features in your existing Notification
component, it may look a little mess-
So you need a bunch of conditions and props to handle this and for every changes you are modifying your existing component which violetes open/closed principle.
Now, let’s refactor this component so that for every new feature in Notification, we don’t have to modify this component.
We will create separate component for each type. Each of this component can then have their own condition and styling.
So, we build separate components for each of the type and pass that inside Notification component. In this way, each type’s logic and styling will be independent of each other and we do not have to modify anything inside Notification component. If a new type gets introduced, we will just create a new component and add that in notificationTypes
table. In this way, for any new changes we will not have to modify the existing code but we can build on top of it.
Keeping the open/closed principle in mind while coding not only helps to keep code clean but also makes it maintainable.
That’s it folks. Thanks for reading!