ogirginc ogirginc - 15 days ago 6
Ruby Question

Parameters in Dynamic Type Checking

In Practical Object-Oriented Design In Ruby by Sandi Metz, she explains -perfectly- the problems in the example above:

class Trip
attr_reader :bicycles, :customers, :vehicle

def prepare(preparers)
preparers.each { |preparer|
case preparer
when Mechanic
# ...
when TripCoordinator
# ...
when Driver
# ...
end
}
end
end

class Mechanic
# ...
end

class TripCoordinator
# ...
end

class Driver
# ...
end


However;
preparers
parameter being dynamic, is it considered a disadvantage, in this case, from a statically type checking language's perspective?

Answer

What is an advantage and what is a disadvantage depends on each programmer and the task at hand.

The flexibility brought by dynamic types is very powerful for some scenario and a poor case for others. C# for instance allows a bit of everything (see dynamic type) which do not make any advantage or disadvantage per se.

What you are describing in your example is called a delegate pattern and has been covered and integrated into ruby quite successfully (my opinion). You have a bunch of documentation on the topic.

The main disadvantage with your example is that you have a switch that needs to be edited when you add/remove types of Preparer. It's not as flexible as you could expect from a dynamic code. Look at delegation patterns, injection and interface and you'll be fine at writing dynamic code that sustains itself.