Skip to content

Instantly share code, notes, and snippets.

@Mardiniii
Last active May 30, 2018 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mardiniii/f4e3538c3761bb9cb9fe2fcc87f8bbf2 to your computer and use it in GitHub Desktop.
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.
# 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