Open/Closed Principle in Ruby

Open/Closed Principle in Ruby

Assume that we already had the code:

1
2
3
4
5
6
7
8
9
class Report
  def body
    generate_reporty_stuff
  end

  def print
    body.to_json
  end
end

The code above violates Open/Closed Principle as if we want to change the format the report gets printed, we need to change the code of the class. Let make it be better then:

1
2
3
4
5
6
7
8
9
class Report
  def body
    generate_reporty_stuff
  end

  def print(formatter: JSONFormatter.new)
    formatter.format body
  end
end

This way changing the formatter is as easy as:

1
2
report = Report.new
report.print(formatter: XMLFormatter.new)

So far so good, I have extended the functionality without modifying the code. In this example, I have used a technique called “Dependency Injection”. That’s it!!! See ya!!! :)