LSP: Liskov Substitution Principle in Swift (with code examples) — SOLID Principles

Gizem Türker
3 min readJun 29, 2022

“Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.”

source

LSP says: These components, which we have listed from private to general, should be open to expansion and closed to change.

· Methods

· Classes

· Packages

· Modules

· Systems

Why do we need LSP?

As we mentioned in OCP, the code’s maintenance is one of the elements we need to be necessary. Therefore, it was necessary to comply with OCP for maintenance and reusable code. We also need to develop the code here using inheritance and interface.

  • It ensures that you are getting your abstractions right. The whole point of creating a class based on an abstract class is that you can use the derived class seamlessly, without having to touch any of the other derived classes and without breaking any builds.
  • It’s an exceptional tool for detecting poor designs.
  • Your unit test and base class’s integration code are fully reusable for your derived classes.

(Bad) Example

We’ll solve that problem more efficiently if we prefer composition over inheritance. Creating a protocol to centralize the same behavior structures should have provided that.

(Better) Example

LSP says: Programs that reference an object from a base class must be able to use an object of a derived class without behavior differences and without knowing about its existence.[source]

The LSP is about building hierarchies with predictable behavior. It’s not enough for sub-class instances to provide all declared methods in their parent class. These methods should also behave appropriately. If you give your client an object, which substitutes its ancestor with a violation of LSP, you might break your client’s assumptions regarding the behavior of the object used by him. A client method should not be able to distinguish whether it works with some class or its descendant by behavior.

We also ensured that immutability is a simple and compelling concept that respects many software-design principles.

We must apply the same fundamentals we used here at OCP-Open/Close Principle. Besides, choosing composition over inheritance makes things easier.

This was the second article of the series of five about SOLID and its use in Swift. I hope you have enjoyed it.

Discuss in the comment.

Follow the LinkedIn, Twitter, and Github.

What is the SOLID Principle?

SRP: Single Responsibility Principle in Swift (with code examples) — SOLID Principles

OCP: Open/Closed Principle in Swift (with code examples) — SOLID Principles

LSP: Liskov Substitution Principle in Swift (with code examples) — SOLID Principles

Interface Segregation Principle in Swift (with code examples) — SOLID Principles

--

--

Gizem Türker

iOS Developer | SwiftUI | Swift 📲👩🏽‍💻 | Speaker | Ex-founder @peltontech