uohzxela / clean-code-ruby

🛁 Clean Code concepts adapted for Ruby
MIT License
1.57k stars 159 forks source link

Better example for "Favor functional programming over imperative programming" #20

Open garethrees opened 5 years ago

garethrees commented 5 years ago

I don't disagree with the sentiment here, but Favor functional programming over imperative programming states that "Functional languages are cleaner and easier to test".

The test for the example doesn't change between implementations, so doesn't give the reader an indication of why functional style is easier to test.

require 'minitest/autorun'

class FunctionalVsImperativeTest < Minitest::Test
  def test_imperative
    calculator = Imperative.new
    assert_equal(calculator.calculate(test_data), 3150)
  end

  def test_functional
    calculator = Functional.new
    assert_equal(calculator.calculate(test_data), 3150)
  end

  private

  def test_data
    [ { name: 'Uncle Bobby',
        lines_of_code: 500 },
      { name: 'Suzie Q',
        lines_of_code: 1500 },
      { name: 'Jimmy Gosling',
        lines_of_code: 150 },
      { name: 'Grace Hopper',
        lines_of_code: 1000 } ]
  end
end

class Imperative
  def calculate(programmer_output)
    total_output = 0

    programmer_output.each do |output|
      total_output += output[:lines_of_code]
    end

    total_output
  end
end

class Functional
  INITIAL_VALUE = 0

  def calculate(programmer_output)
    programmer_output.sum(INITIAL_VALUE) { |output| output[:lines_of_code] }
  end
end
uohzxela commented 5 years ago

That's a great point. I'd be happy to merge any PRs that can replace this example with a better one!