Skip to content

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

Description

@garethrees

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

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions