Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
garethrees opened this issue Nov 25, 2018 · 1 comment

Comments

@garethrees
Copy link

garethrees commented Nov 25, 2018

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants