Dependency Injection, What is it?

To understand Dependency injection it is first critical to know about Concrete Dependency. That is where one object has a directly linked dependency on another object within your program. As the following example illustrates.

class Rail_Journey

end

class Journey_log

  def initialize
    @journey = Rail_Journey.new
  end
end  

In the example we have setup a concrete dependency where our Journey_log class is intrinsically linked to carrying out journeys by rail.

So what is the big deal?!

What about journeys that don't involve travelling by rail? In order to implement this functionality you would need to create the class for the other journey type AND change the dependency within the Journey_log class.

Far better would be to use Dependency Injection to allow us to pass in whatever type of journey we want as the following code shows:

class Rail_Journey

end

class Bike_Journey

end  
class Journey_log

  def initialize(journey_klass)
    @journey = journey_klass
  end
  def make_journey
    new_journey = @journey.new
  end
end  

The above uses the principle of Dependency Injection by allowing us to pass in any class. Keeping our code modular and also pushing our decision about which type of object to use as close to runtime as possible.