Hey, Mom! The Explanation.

Here's the permanent dedicated link to my first Hey, Mom! post and the explanation of the feature it contains.

Tuesday, July 23, 2019

A Sense of Doubt blog post #1615 - OOP vs. Functional Programming

https://blog.soshace.com/en/2019/05/22/functional-vs-object-oriented-programming/
A Sense of Doubt blog post #1615 - OOP vs. Functional Programming

As the summer unspools and I am embroiled in a job search, I am once again studying programming concepts in an effort to less like an impostor and feel better ownership of the things I actually do know. I know stuff.

But recently, I could not access all my memories when someone asked me about OOP style of programming (Object Oriented Programming) versus functional style. I had a rough memory of the debate. I knew functional was a stricter style of programming that adhered more to mathematical models, algebraic functions (well, Lambda Calculus). I knew that functional protected data types better, despite the data hiding of OOP, and as I spoke with the person who asked for my thoughts on the OOP vs. functional debate, I remembered that functional style saved the state of data and kept it immutable.

I learned OOP in school, and, oddly, functional style was not even discussed as another option or maybe just not in those words.

Looking at the list of functional languages, I did not learn any of them in school and have only started to teach myself Javascript since leaving WMU and my programming studies.

Before today's shared article, here's some resources and explanations.

Good functional explanation - https://www.geeksforgeeks.org/functional-programming-paradigm/

(I love Geeks for Geeks...)

Programming Languages that support functional programming: Haskell, JavaScript, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket.

Great article on a simple OOP explanation from a site I commonly work with all the time:

https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/

POPULAR OBJECT-ORIENTED LANGUAGES
  • Simula, the first object-oriented programming language
  • Java
  • Python
  • Ruby
  • C++
  • Smalltalk
  • Visual Basic .NET
  • Objective-C: OOP is a core tenet of iOS mobile app programming, and Objective-C is essentially the C language with an object-oriented layer.
  • Curl
  • Delphi
  • Eiffel

BTW, the caption link for the image in the banner is a good source and worth reading.

https://www.reddit.com/r/ProgrammerHumor/comments/418x95/theory_vs_reality/


When it comes to MY SIDE of this debate, I do not want to take a hard line of one over the other. Given that I have written quite a bit of OOP code and very little functional, I would like to try more functional code.

I LIKE what Gathen shares at the end, which comes from another blog, which I included: when working with just data, functional works better, and when working with PEOPLE, then OOP seems to make more sense. I am going to have to think about that opinion, but my first impression is that I like it.

PREVIOUSLY, I shared an article (just last year) on this issue, at this link -

https://sensedoubt.blogspot.com/2018/10/a-sense-of-doubt-blog-post-1321-goodbye.html

Today's main shared article (because there's other stuff above and a short snippet after the main share) is a very well written and even humorous article (a style to emulate!) published on the Code Newbie site.

It's an enjoyable read. I tried to find bio information on the author and came up with nothing.

I like the explanation of OOP and Functional styles Bill Gathen details in this post from 2015 as the content is still relevant today and subject to versions of any programming languages.

Remember, my blog is more dedicated to MY STUDY than it is to MY TEACHING, and so here's some of what I have studied.

Enjoy.

Today's share is - FROM -
https://www.codenewbie.org/blogs/object-oriented-programming-vs-functional-programming




Object Oriented Programming vs. Functional Programming





If you’ve spent much time in online tech forums or following technical folks on Twitter, you’ve probably heard an ongoing debate about the relative merits of Object-Oriented Programming (OOP) and Functional Programming (FP). What are they and how do they differ? Is one a better choice than the other?
I’ll answer the last question first. Is one a better choice than the other? It depends on what your program is trying to do. To make that decision we’ll have to dig deeper. Let’s start with some Wikipedia definitions:
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods -- Wikipedia https://en.wikipedia.org/wiki/Object-oriented_programming
Functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data -- Wikipedia https://en.wikipedia.org/wiki/Functional_programming
These are acceptable descriptions if you already understand the concepts they’re describing, but not helpful if you don’t. Let’s see if we can do better.
Both OOP and FP have the shared goal of creating understandable, flexible programs that are free of bugs. But they have two different approaches for how to best create those programs.
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). OOP says that bringing together data and its associated behavior in a single location (called an “object”) makes it easier to understand how a program works. FP says that data and behavior are distinctively different things and should be kept separate for clarity.
Let’s look at some examples of the two approaches. I’m using Ruby because it natively supports both styles and is easy to read for non-rubyists, but other languages also support both, such as JavaScript and Scala.

Let’s say you run a company and you’ve just decided to give all your employees a $10,000.00 raise. (If this sort of thing happens often at your company, let me know when you’re hiring) How could we write a command-line script to make this change?
You most likely have all your employee records in a database with two attributes: the employee’s name and a current salary. In our examples, we’ll ignore the part where you transfer the data to and from the database. Let’s just focus on the “giving a raise” feature.
Here’s one approach using OOP:
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
This is our class, which we’ll use to generate new Employee objects. Most OOP languages use classes to generate objects in the same way a cook uses recipes to create meals -- the classes tell us how to construct the object, how it should behave, what it looks like, etc.
The @-sign before a variable makes it an “instance” variable: a variable that lives inside the object (aka instance) and can be used in its methods without having been passed in as an argument, the way change_salary uses @salary. The initialize method takes the name and salary we passed to new and stores them in the @name and @salary instance variables.
All the methods except for initialize are “instance methods” which also live inside the object (aka instance) and can be called on the object itself.
Now we’ll generate some objects to work with.
employees = [
  Employee.new("Bob", 100000.0),
  Employee.new("Jane", 125000.0)
]
Each Employee.new(...) call creates an object with data (@name and @salary) and behavior (change_salary and description). We call new twice, which gives us a pair of objects representing Bob and Jane stored in an array we are calling “employees”. In a normal app, this array of objects will typically be returned from the database directly by a tool such as ActiveRecord.
Now let’s give out those raises.
employees.each do |emp|
  emp.change_salary(10000.0)
end
We call the each method on our array of employees, which hands us each employee in turn and stores it in a local variable called emp. We call the “change_salary” method we defined in our class, passing in a value of 10000.0. This adds our $10K to the employee’s salary and stores the sum in @salary, overwriting the existing value.
employees.each do |emp|
  puts emp.description
end
Finally we can generate some output to make sure the results are what we intended, using the description method to build our output string instead of trying to access the data fields (@salary and @name) directly. This is called “data hiding” and it allows us to change the names of our instance variables without forcing the users of our object to change how they use it.
We use each again to output the results. This time, we use puts (put string) and call the description method for each of our objects to print their description, as we defined in our class.
There are several important things to notice about the OOP implementation. Data is supplied to an object at the time the object is created (when we called the ‘new’ method). Then we use methods on that object (change_salary and description) to interact with data that we’ve already stored. This gives us a good place to put all the behaviors that are associated with that object type, making them easy to find if we’re unfamiliar with the codebase or refreshing our memory after some time away. The names of these methods document object’s behaviors , which also helps us familiarize ourselves with the code. The object is an obvious location to add behaviors as our project becomes more complex.
Let’s implement this task using an FP approach.
employees = [
  [ "Bob",  100000.0 ],
  [ "Jane", 125000.0 ]
]
This time our data structure is an array of arrays instead of an array of objects containing the values. FP prefers to keep data in plain arrays and/or hashes and not “complicate” data by mixing it with behavior.
Instead of converting the data to an object and then calling methods on it, we write a pair of standalone methods called change_salaries (plural) and change_salary (singular). We pass change_salaries two arguments: the array of arrays representing our data and the change amount. change_salaries uses map instead of the each method we used in the OOP version. We’ll discuss map in a moment.
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”. In our example, change_salaries has a single job: call change_salary for each employee in the employees array and return those values as a new array. change_salary also has one job: return a copy of a single employee with the salary field updated. change_salaries delegates the calculation of the new salary to change_salary, allowing change_salaries to focus entirely on handling the set of employees and change_salary to focus on updating a single employee. A nice side-effect of this approach is if we had a single employee we wanted to change the salary for, we could call change_salary directly! Composition isn’t unique to FP -- OOP uses it as well -- but it is a cornerstone of the FP mindset.
happier_employees = change_salaries(employees, 10000.0)
Because we don’t have objects, change_salaries requires that we pass in not just the amount, but also the data we want to modify. This method returns the updated dataset, which we store in the happier_employees variable.
happier_employees.each do |emp|
  puts "#{emp[0]} makes #{emp[1]}"
end
Finally, we use ‘each’ to walk through every record in happier_employees and generate the output message ourselves. This fits the FP model because FP likes to view everything as a data transformation: you start with this dataset, apply these transformations to it (in this case, adding $10K) and generate a new dataset.
Something you’ll notice right off is there are fewer lines of code, mainly because we don’t build the class for creating our objects.
Another subtle -- but important -- difference is that in the OOP version change_salary used each to process each employee, but the FP version uses map. Instead of changing the original value, ’map’ creates a copy of the array containing the return value of each pass. When all elements have been processed, map hands us the copy with all the new values, which we store in happier_employees. The original array is untouched!
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. In the OOP version, the contents of the employees array changes over time: before change_salary is applied the salaries are 100K and 125K, but afterwards they are 110K and 135K! This means we don’t always know which value we’ll have at any given point in the program: we have to walk through the program flow and find out if change_salary has been called or not. This can be difficult as the program increases in complexity. The FP version avoids this because employees represents the “before” state and happier_employees represents the “after” state. Their values are always the same over their entire existence.
So which approach should you choose for your next project?
Michael Fogus, author of “Functional JavaScript”, suggests in his blog post “FP vs OO, from the trenches” (http://blog.fogus.me/2013/07/22/fp-vs-oo-from-the-trenches/) that when he deals with data about people, FP works well, but when he tries to simulate people, OOP works well. Our example is “data about people” -- since we’re changing the salary directly -- so the FP version is shorter and simpler. If we described a feature like “employee requests time off” that requires a more-complicated interaction with the data -- likely creating a “time-off request” object attached to the employee -- then OOP might be a better fit. Hardcore OOP or FP developers could explain why their approach is better in either situation, which makes this debate so interesting. Read the comments on the post for an example of the dialogue that surrounds OOP and FP.
If you’re on a tight schedule and are already familiar with one approach or the other, stick with what you know. If it’s a personal project or you have some flexibility with deadlines, it might be worth trying each approach for a feature and seeing which results in a more pleasing, clear solution. We’ve only scratched the surface, and the problems you’re solving may look nothing like the trivial one I used in my example. Explore both and use your best judgement.

http://blog.fogus.me/2013/07/22/fp-vs-oo-from-the-trenches/

FP vs. OO, from the trenches.
Jul 22, 2013
I’ve been programming for quite some time and have explored a variety of programming paradigms along the way. From time to time people will ask1 which is better: functional programming or object-oriented programming. Having done both extensively in my time I can exclaim a resounding: it depends.
Lame.
While I’ll never be a major player in the grand Internet flame war, I will say that I’ve had great success following a simple two-point guideline:2
  • Whenever I write some code to deal with data about people then functional programming seems to work best.
  • Whenever I write some code to simulate people then object-oriented programming seems3 to work best.
YMMV.4
:F


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


- Bloggery committed by chris tower - 1907.23 - 10:10

- Days ago = 1480 days ago

- New note - On 1807.06, I ceased daily transmission of my Hey Mom feature after three years of daily conversations. I plan to continue Hey Mom posts at least twice per week but will continue to post the days since ("Days Ago") count on my blog each day. The blog entry numbering in the title has changed to reflect total Sense of Doubt posts since I began the blog on 0705.04, which include Hey Mom posts, Daily Bowie posts, and Sense of Doubt posts. Hey Mom posts will still be numbered sequentially. New Hey Mom posts will use the same format as all the other Hey Mom posts; all other posts will feature this format seen here.

No comments: