Tuesday, March 08, 2016

Dependency Inversion Principle Example from The RSpec Book

The code example for Codebreaker game from The Rspec Book. The solution in the book that does not apply the DIP

Before

module Codebreaker
  class Game
    def initialize(output)
      @output = output
    end

    def start(secret)
      @secret = secret
      @output.puts 'Welcome to Codebreaker!'
      @output.puts 'Enter guess:'
    end
  end
end

g = Codebreaker::Game.new($stdout)
g.start('sekret')

The solution after applying the DIP.

After

module Codebreaker
  class Game
    def initialize(writer)
      @writer = writer
    end

    def start(secret)
      @secret = secret
      @writer.write 'Welcome to Codebreaker!'
      @writer.write 'Enter guess:'
    end
  end
end

class StandardConsole
  def write(message)
    $stdout.puts(message)
  end 
end

writer = StandardConsole.new
g = Codebreaker::Game.new(writer)
g.start('sekret')

No comments:

Post a Comment