alishahUK's avatar

Liskov Substitution Principle

Hey guys,

I am trying to come up with a real world example for Liskov substitution principle in an ecommerce application context. Now I understand the principle, however, I am struggling to come up with a really good use case. Can any body help out, please?

0 likes
6 replies
bobbybouwmann's avatar

Mmh I think I have an example for you.

Let's say you have a shop where you sell books and ebooks. Now not all books are available as downloadable content and not every book is available as a hard copy right. But some books have both. So for each book the action after purchasing is different. So either ship the book or download the book

So you have a base class called book and then for each possibility you have an implementation for that.

class Book
{
    public function getTitle();
    public function getSummary();
    public function purchase();
}

class DownloadableBook extends Book
{
    public function purchase()
    {
        // Perform the download action
    }
}

class PhysicalBook extends Book
{
    public function purchase()
    {
        // Perform the shipping thing
    }
}

I believe this is a correct example ;)

1 like
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

Response of purchase method from all classes should be the same, otherwise the principle is violated.

I'll try to explain, but obviously in my example is not where to use Liskov Substitution Principle

Let's imagine from start your shop had only PhysicalBook, after every purchase, the purchase method return to the frontend and response with 3 keys: \

  • status http status \
  • message to display to the user \
  • bookId to show the user link to the book he/she just bought.
{
    'status': 200,
    'message': 'Success',
    'bookId': 1
}

Now you introduce DownloadableBook, and in purchase you return only 2 keys\

  • status http status \
  • message to display to the user
{
    'status': 200,
    'message': 'Success',
}

and here is the violation, link to the book will be broken in frontend, the API is different. Hope this helps.

1 like
alishahUK's avatar

Thank you @sergiu17 , I think that makes more sense. Much appreciated. I thought I can mark your and @bobbybouwmann answers best at the same time lol. However, I can mark only one answer best. Thank you both for your time

bobbybouwmann's avatar

Very nice example @sergiu17 That is exactly what I meant with my example but it was too abstract I guess!

1 like

Please or to participate in this conversation.