ogirginc
ogirginc

Reputation: 5270

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?

Upvotes: 0

Views: 61

Answers (2)

muichkine
muichkine

Reputation: 2940

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.

Upvotes: 1

dsn raghavendra rao
dsn raghavendra rao

Reputation: 196

check this code

class Trip
   attr_reader :bicycles, :customers, :vehicle

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

Here case preparer.class.name returns class name

Upvotes: 0

Related Questions