Last active
May 30, 2018 21:51
-
-
Save Mardiniii/f4e3538c3761bb9cb9fe2fcc87f8bbf2 to your computer and use it in GitHub Desktop.
Open-closed Principle: Objects or entities should be open for extension, but closed for modification.
This file contains hidden or 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
# Violates OCP | |
class InvoiceNotifier | |
def initialize(invoice) | |
@invoice = invoice | |
end | |
def notify(channel) | |
case channel | |
when 'email' | |
send_email | |
when 'sms' | |
send_sms | |
when 'letter' | |
send_letter | |
else | |
raise NotImplementedError | |
end | |
end | |
def send_email | |
# Logic to send email notification | |
end | |
def send_sms | |
# Logic to send sms notification | |
end | |
def send_letter | |
# Logic to send letter notification | |
end | |
end | |
# Enforces OCP | |
class InvoiceNotifier | |
def initialize(invoice, notifier: InvoiceMailer.new) | |
@invoice = invoice | |
@notifier = notifier | |
end | |
def notify | |
@notifier.send(@invoice) | |
end | |
end | |
class InvoiceMailer | |
def send(invoice) | |
# Send notification using email | |
end | |
end | |
class InvoiceSMS | |
def send(invoice) | |
# Send notification using sms | |
end | |
end | |
class InvoiceLetter | |
def send(invoice) | |
# Send notification using letter | |
end | |
end | |
# Some examples | |
# Send invoice email | |
InvoiceNotifier.new(@invoice).notify | |
# Send invoice SMS message | |
InvoiceNotifier.new(@invoice, notifier: InvoiceSMS.new).notify | |
# Send invoice regular email letter | |
InvoiceNotifier.new(@invoice, notifier: InvoiceLetter.new).notify |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment