OO Programming vs Functional Programming

In all programs, there are two primary components: the data (the stuff a program knows) and the behaviors (the stuff a program can do to/with that data).

Object-Oriented Programming: programming paradigm that brings together data and its associated behaviors (functions) in a single location called an “object”.

  • data structure is usually an array of objects.  (Data is converted into objects and methods are called on them).

Example:

class Employee
  def initialize(name, salary)
    @name = name
    @salary = salary
  end

  def change_salary(amt)
    @salary = @salary + amt
  end

  def description
    "#{@name} makes #{@salary}"
  end
end
employees = [
  Employee.new("Bob", 100000.0),
  Employee.new("Jane", 125000.0)
]

employees.each do |emp|
  emp.change_salary(10000.0)
end

employees.each do |emp|
  puts emp.description
end

Functional Programming: programming paradigm that says data and behavior are distinctively different things and should be kept separate for clarity.

  • data structure is an array of arrays and/or hashes to not *complicate* data by mixing it with behavior.
  • FP leans very heavily on tiny methods that do one small part of a larger job, delegating the details to other tiny methods. This combining of small methods into a larger task is call “composition”.
  • This idea of not changing the contents (or “state”) of a variable once it’s been created is called immutability and is another key aspect of FP.

Example:

employees = [
  [ "Bob",  100000.0 ],
  [ "Jane", 125000.0 ]
]
happier_employees = change_salaries(employees, 10000.0)
happier_employees.each do |emp|
  puts "#{emp[0]} makes #{emp[1]}"
end
OO Programming vs Functional Programming