← Back to Upcase

Polymorphism & Ruby (blog post)

(Ralph Wintle) #1

Hi everyone,

I just read the blog post Back to Basics: Polymorphism & Ruby, and I’ve sort of been playing around with similar examples in my code and would appreciate yourt feedback!

In the last two examples of the blog post , there is a refactoring of the parse method which initially uses a conditional to check type in order to determine which parser to use.

The new example uses Polymorphism to separate concerns and apply the Single Responsibility Principle. Instead of asking the object what type of thing it is, the code is now telling the Parser ‘hey use this type of parser’, which I agree is better and easier to understand.

This makes sense to me, however it doesn’t seem to replicate the original parse method in that we’re still required to tell the Parser which type of Parser (XmlParser/JsonParser) to use?

Just to extend the example, would you consider adding another class to determine which parser to use?

Something like below:

class Parser
  def initialize(file)
    @file = file

  def parse


  attr_reader :file

  def parser
class FindParser
  def initialize(file)
    @file = file
    @xml_parser = XmlParser.new
    @json_parser = JsonParser.new

  def return_parser
    # Determine whether to return an XmlParser or JsonParser
    # Most likely use a conditional again?
# Putting it all together 

I appreciate the blog post uses a contrived example for the purposes of the explaining it’s point, however I’m just trying to get a better understanding of polymorphism and how it can be applied, hence the example above.

Do we still need to run a conditional check to determine which Parser (e.g. FindParser class) or is there a better way?