Skip to content

Instantly share code, notes, and snippets.

@Mardiniii
Last active May 30, 2018 18:17
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/4114c4ed87dafba0071cad87a526fcdf to your computer and use it in GitHub Desktop.
Save Mardiniii/4114c4ed87dafba0071cad87a526fcdf to your computer and use it in GitHub Desktop.
Dependency Injection Principle: Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.
# Violates DIP
class InvoiceNotifier
def initialize(invoice)
@invoice = invoice
end
def mail_notification
InvoiceMailer.new.send(@invoice)
end
def sms_notification
InvoiceSMS.new.send(@invoice)
end
def letter_notification
InvoiceLetter.new.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
# Enforces DIP
class InvoiceNotifier
def initialize(invoice)
@invoice = invoice
end
def notify(notifier: InvoiceMailer.new)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment