Liskov substitution
Lesson 24 of 28 in Coddy's Clean Code - Write better code using Python course.
"Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it."
This principle states that a child class must be substitutable from its parent class.
For example,
class Notification(ABC):
@abstractmethod
def notify(self, message, email):
pass
class Email(Notification):
def notify(self, message, email):
print(f'Send {message} to {email}')
class SMS(Notification):
def notify(self, message, phone):
print(f'Send {message} to {phone}')As you can see both SMS and Email inherit from Notification but one is sending to email and one to phone, the SMS class is not substitutable from it's parent Notification!
Challenge
MediumFix the given code to apply Liskov substitution princple -
- notify function should only get message as argument.
- Email and SMS should each have constructor which will initiate email and phone accordingly.
- edit the code to apply the changes
This is only one suggested solution to apply Liskov principle there are more that will work!
Try it yourself
from abc import ABC, abstractmethod
class Notification(ABC):
@abstractmethod
def notify(self, message, email):
pass
class Email(Notification):
def notify(self, message, email):
print(f'Send {message} to {email}')
class SMS(Notification):
def notify(self, message, phone):
print(f'Send {message} to {phone}')
if __name__ == '__main__':
email = input()
phone = input()
message = input()
notification1 = Email()
notification2 = SMS()
notification1.notify(message, email)
notification2.notify(message, phone)