II. Open-Closed Principle in Swift
Continuing with the series of SOLID principles we will talk in this post about the Open-Closed principle. If you didnt’ heard about SOLID, here is the first post where we talk about the meaning of SOLID and the first principle, the Single Responsibility.
Open Closed principle says that our code must be open to extension but closed to modification. In other words, the new functionalities must be implemented by adding new code without modifying the existing one.
How do we achieve this?
We can do it through inheritance, composition and polymorphism.
In swift we have the extensions that are a good way to add new behaviors without modifying the existing code.
For example, continuing with the previous example where we had the ShopNetwork class responsible to retrieve network information.
The OrderController hold an instance of ShopNetwork class which call fetchOrder method in the viewdidload method. But imagine that now we need to return the cache stored information in case that the user doesn’t have internet. How could we add this functionality without breaking the code as little as possible?
We could create a protocol that defines a common interface to work with different Frameworks and each class would implement this protocol where the logic will take place extending the functionality.
In our OrderController instead of having a dependency to a class, we have a dependency with the protocol, so we depend on the abstraction not on a concrete implementation.
By this way we can inject the type of abstraction with the service we want, expanding the functionality and avoiding breaking the code for a new StorageService.
Keep in mind that it is not always practical and almost impossible to have a 100% open / closed code. But we can pay attention to the use of structures such as enum since they are prone to being modified before new changes producing cascading changes in switch or if-else blocks.
As far as possible we must have a code that avoids having to change the existing code in other modules. If when adding code we are constantly changing a part of the code, we are surely breaking this principle and as we saw earlier this can be avoided by using abstraction.
I hope this post has been helpful and I wait for you in the next one where we will talk about the Liskov Substitution principle also closely related to this principle.
Happy coding!👨💻