Skip to content

Instantly share code, notes, and snippets.

@omedale
Created April 22, 2019 20:43
Show Gist options
  • Save omedale/e1797da8fd08bc51cd157d4758d0b58c to your computer and use it in GitHub Desktop.
Save omedale/e1797da8fd08bc51cd157d4758d0b58c to your computer and use it in GitHub Desktop.
Dependency Inversion Principle
# 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