Skip to content

Instantly share code, notes, and snippets.

@omedale
Last active April 30, 2019 10:37
Show Gist options
  • Save omedale/f5d9301688ebe018a7a0b7e4bf2e20dd to your computer and use it in GitHub Desktop.
Save omedale/f5d9301688ebe018a7a0b7e4bf2e20dd to your computer and use it in GitHub Desktop.
Open-Close Principle
# This is a bad solution that violates open-closed principle
class Document
def initialize(path, doc_type)
@path = path
@doc_type = doc_type
end
def parse
case doc_type
when :docx
# some docx parsing functionality
when :pdf
# some pdf parsing functionality
end
end
end
# A good example where all extensions are made according to the open/closed principle
class Document
def initialize(path, parser_class)
@path = path
@parser_service = parser_class.new(@path)
end
def parse
parser_service.parse
end
end
class BaseDocumentParser
def initialize(path)
@path = path
end
end
class PdfDocumentParser < BaseDocumentParser
def parse
p 'some pdf parsing functionality'
end
end
class DocxDocumentParser < BaseDocumentParser
def parse
p 'some docx parsing functionality'
end
end
#we can now extend our Document class functionality without modifying it.
#When we need to add a new document type, we will not have to modify the Document class.
Document('paths', PdfDocumentParser).parse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment