Thay thế Liskov
Bài học 24 trên 28 trong khóa học Clean Code: viết code tốt hơn với Python của Coddy.
"Các hàm dùng con trỏ hoặc tham chiếu đến lớp cơ sở phải có thể dùng các đối tượng thuộc lớp dẫn xuất mà không cần biết đó là đối tượng của lớp nào."
Nguyên tắc này nêu rằng lớp con phải có thể thay thế lớp cha.
Ví dụ:
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}')Như bạn thấy, cả SMS và Email đều kế thừa từ Notification, nhưng một lớp gửi đến email, còn lớp kia gửi đến phone. Lớp SMS không thể thay thế lớp cha Notification!
Thử thách
Trung bìnhSửa code đã cho để áp dụng nguyên lý thay thế Liskov:
- Hàm notify chỉ nhận message làm đối số.
- Email và SMS mỗi lớp cần có hàm khởi tạo để khởi tạo lần lượt email và phone.
- chỉnh sửa code để áp dụng các thay đổi
Đây chỉ là một lời giải gợi ý để áp dụng nguyên lý Liskov, còn nhiều cách khác cũng hiệu quả!
Tự làm thử
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)
Tất cả bài học trong Clean Code: viết code tốt hơn với Python
Tự luyện tập: Trình biên dịch Python online