Created
April 22, 2019 20:43
-
-
Save omedale/e1797da8fd08bc51cd157d4758d0b58c to your computer and use it in GitHub Desktop.
Dependency Inversion Principle
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
# Violation of the Dependency Inversion Principle in Ruby | |
# The class Printer depends on classes PdfFormatter and HtmlFormatter which are low-level objects | |
class Printer | |
def initialize(data) | |
@data = data | |
end | |
def print_pdf | |
PdfFormatter.new.format(@data) | |
end | |
def print_html | |
HtmlFormatter.new.format(@data) | |
end | |
end | |
class PdfFormatter | |
def format(data) | |
# format data to Pdf logic | |
end | |
end | |
class HtmlFormatter | |
def format(data) | |
# format data to Html logic | |
end | |
end | |
#Correct use of the Dependency Inversion Principle in Ruby | |
#Refactor Printer class by ensuring the printer ‒ a high-level object | |
#doesn’t depend directly on the implementation of low-level objects ‒ the PDF and HTML formatters | |
class Printer | |
def initialize(data) | |
@data = data | |
end | |
def print(formatter: PdfFormatter.new) | |
formatter.format(@data) | |
end | |
end | |
class PdfFormatter | |
def format(data) | |
# format data to Pdf logic | |
end | |
end | |
class HtmlFormatter | |
def format(data) | |
# format data to Html logic | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment