Learning Open-Closed Principle
Introduction to the Open-Closed Principle
The Open-Closed Principle states that software entities — including classes, modules, and functions — should be open for extension but closed for modification. That is, one should be able to extend the behavior of the entities without modifying the existing working code.
Once you’ve created an entity that functions properly and is likely published, you shouldn’t modify it. However, you may need to reuse the entity and enhance its capabilities. In certain cases, you may need to modify how some parts of the entity operate. This principle lets you achieve these objectives.
Advantages of the Open-Closed Principle
This principle enables the reuse of legacy code, libraries, and other closed or protected source codes. It allows for the extension of functionality without altering the existing code. This ensures that the tested code will continue to work as expected even after updating it.
Exploring an Example Use Case
At a restaurant, the chef follows a strict process to prepare pizza. However, the chef can also add toppings and other customizations that suit the customer’s preference. In open-closed principle terms, you’d say the menu is closed for modification but open for extension.
In the next demo, you’ll modify your e-commerce app to follow this principle.