III. Liskov Substitution Principle in Swift

Rafael Asencio
2 min readAug 12, 2021

We continue with the Liskov Substitution principle. In the last post where we talked about the Open/Closed principle we mentioned that it is closely related to it and now we will see why. Since in the Open/Closed principle we managed to have a more scalable and maintainable system through inheritance and the use of abstractions, in this case we are also going to focus on these aspects as well.

This principle, which owes its name to the renowned engineer Barbara Liskov, is fundamental in object-oriented programming. The principle tells us that objects of a superclass must be replaceable by objects of its subclasses without causing different behaviors in the application.

In the previous example we can see how through our dependence on the abstraction ‘StorageService’ we could choose between LocalService or RemoteService to obtain information about the orders. therefore we also comply with this principle since when substituting objects of a superclass we wouldn’t have any problem. Each subclass would have its logic to obtain the data but without affecting behavior.

We have to understand that all these principles are related to each other, they don’t go separately, they all apply together. Here we have another example of this principle.

Imagine that we have different ways of accessing the app, with Facebook, Google or Apple. We could create a common interface ‘LoginServiceProtocol’ from which each class inherits separately and inject the login method by pressing the button.

By this way we can inject different login methods that inherits from a common superclass without having any kind of problem and respecting the Liskov Substitution principle.

In the next post we will see what problems can arise from this principle and how we can solve it with the Interface Segregation principle.

I hope it has been helpful and happy coding! 👨‍💻

--

--