SOLID: Liskov Substitution Principle(LSP)

LSV is actually an extension to OCP.
Meaning, it helps to correct your OCP implementation correct way.

If S is a subtype of T, then objects of type T may be replaced with objects of type S, without breaking the program

Objects of a super class should be replaceable with the object of Sub Classes

Let understand this with a violation

See Here, Can not replace the Super Class object with subtype means there is some design issue

Because, SUB CLASS not behaving the same way as SUPER CLASS. It is not delivering the package directly. It is awaiting user’s input to proceed.

Two implementation of the same interface or protocol can be used interchangeably without unexpected behaviour.

Let’s see an example,
There is a web service interface which can be used in the application and also for the unit tests. But in unit tests the FeedService would be mock.

Feed Screen which lists all the feeds using the feed service injected into it.

Now let’s see how the FeedService can be implemented for real network and mock network and understand what is the violation and how to fix it.

Mock Implementation for the Unit Test

So far what we have done is nothing but the OCP, but how to make sure that our OCP is correct or not. Tada, here comes the LSP.

Here URLNetwork and MockNetwork are the implementations for the protocol/interface FeedWebService

But for MockNetwork, it is not returning the completion on main thread which we expect as per protocol design
(This is also called the Design By Contract or Design by protocol violation).

Therefore we would not be able to swap this two implementation without changing the code which is LSP violation
If we try to swap webService with mockWebService , it would break the UI operations which expecting main thread.

Read the definition again and it would be more clear after this example, Try!

So to solve this we can make the MockNetwork ‘s implementation to return on main thread only to avoid unexpected behaviour and follow LSP.

See, how LSV allows you to make sure that your OCP is done properly.

Lets move to the next topic Interface Segregation Principle

iOS Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store