Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
We have notification system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NotificationSender | |
def send(user, message) | |
EmailSender.send(user, message) if user.active? | |
end | |
end |
But if we need to chose - send sms or email? So we can add something like if else, but the good way is to create another services
It's a way from Design Patterns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sender | |
def send(user:, message:) | |
raise NotImplementedError | |
end | |
end | |
class EmailSender < Sender | |
def send(user:, message:) | |
# implementation for Email | |
end | |
end | |
class SmsSender < Sender | |
def send(user:, message:) | |
# implementation for SMS | |
end | |
end | |
sender = NotificationSender.new | |
sender.send(user, "Hello World", SmsSender.new) |
http://rubyblog.pro/
Comments
Post a Comment