iOS — Open-Closed principle by example
Classes should be open for extension but closed for modification
--
The main idea of this principle is to keep existing code from breaking when you implement new features. Which means instead of changing the code of the class directly, you can create a subclass and override parts of the original class that you want to behave differently by that you will achieve your goal but also won’t break any existing clients of the original class, while if a class is already developed, tested, reviewed and included in some framework or otherwise used in an app, trying to mess with it’s code is risky.
Keep in mind that this principle is not meant to be applied for all changes to a class. If you know that there’s a bug in the class, just go on and fix it; don’t create a subclass for it. A child class should not be responsible for the parent’s issues.
Example
Let’s say we have an e-commerce application with an Order class that calculates shipping costs and all shipping methods are hard coded inside the class. If you need to add a new shipping method, you have to change the code of the Order class and risk breaking it.
Start by extracting shipping methods into separate classes with a common interface which leads us to the Strategy pattern.
Now when you need to implement a new shipping method, you can derive a new class from the Shipping interface without touching any of the Order class’ code. The client code of the Order class will link orders with a shipping object of the new class whenever the user selects this shipping methods in the UI.
As a bonus, this solution let you move the delivery time calculation to move relevant classes, according to the single responsibility principle.
This article is written based in Book “Dive into Design Patterns” by Alexander Shvets which I’m reading right now. Feel free to email me (hiadriatik@gmail.com) if you have any questions, challenging opportunities, or you just want to say hi.
Linkedin: https://www.linkedin.com/in/adriatikgashi
Finally, be sure to follow me so that you do not miss any new stories I publish.