Dependency Inversion Principle

Topics: SOLID Principles

The Dependency Inversion Principle says code should depend on abstractions rather than concrete implementations.

The 5th of the SOLID Principles.

“Depend on abstractions, not concrete implementations.”

Bad:

def initialize(counter)
  # concrete dependency gets created
  @counter = MyCounter.new(0)
end

def do_the_thing
  counter.increment
end

Good:

attr_reader :counter

def initialize(counter)
  # abstract dependency gets injected
  @counter = counter
end

def do_the_thing
  counter.increment
end