r/functionalprogramming • • May 31 '20

JavaScript Please help me understand why you should use FP (in Javascript) instead of OOP as this example makes me wonder if FP is just an overcomplex neckbeard hype.

Hey Functional Programming community. A week ago I first watched a talk about Functional Programming in Javascript and learned a lot about it afterwards. But now, a week later, I'm so frustrated. Is it me, do I not understand FP good enough? Or is it just a neckbeard "im the real programmer" hype as it feels like now? Please help me understand the difference and why you would choose for the first approach. Thank you so much!

Okay; All I want is to display a button on a webpage.

The HTML:

<div id="app"></div>

Now we have to create a pure function that will create a HTMLButtonElement:

const newButton = _ => document.createElement("button");

But, we also would like to have a label on our button right? So we need a textNode and append this to our button. Two different functions in Functional Programming:

const newTextNode = text => document.createTextNode(text);
const append = (child, target) => { target.appendChild(child); return target };

Now we need an other function to combine all these functions to create some function inception just to create our fucking button and have it in the right order as well:

const button = label => append(newTextNode(label), newButton());

Finally we can create our button and append it to the body:

const myButton = button("Click me!");
document.body.append(myButton);

To have an end result of this pile of shit:

const newButton = _ => document.createElement("button");
const newTextNode = text => document.createTextNode(text);
const append = (child, target) => { target.appendChild(child); return target };
const button = label => append(newTextNode(label), newButton());

const myButton = button("Click me!");
document.body.append(myButton);

This seems to me like it's overly complex. Especially when we have this super simple, human understandable OOP version:

class Button {
    constructor(label) {
        const button = document.createElement("button");
        const btnLabel = document.createTextNode(label);
        
        button.appendChild(btnLabel);
        return button;
}

const myButtonOOP = new Button("Click Me!");
document.body.append(myButtonOOP);

Please help me understand why one would prefer the first, the FP approach, over the latter, the OOP approach. Especially when we would like to add an, for example, callback to the button. In the OOP version all we have to do is alter the constructor making the callback optional for reverse compatibility:

constructor(label, callback = false)

And we have to add the event Listener if a callback is present:

if(callback) {
    button.addEventListener("click", callback);
}

If we would like to do the same, super simple change, to the Functional approach. We have to create this function inception that's almost unreadable. I'll probably write it completely wrong as it's too complex to come up with:

const listen = (target, callback) => target.addEventListener("click", callback);
const button = (label, callback = false) => listen(append(newTextNode(label), newButton(), callback);

It just doesn't make sense to me. The latter is so disgustingly unreadable?

I get that the pure functions are an amazing concept that make a lot of sense. But at what cost?

0 Upvotes

7 comments sorted by

24

u/[deleted] May 31 '20

Rule number 1 in this subreddit is to be respectful and nice to each other. Your rant begins by describing functional programmers as “neckbeards” and gets worse from there. This is not okay.

Three general points of advice:

  1. Neither the FP nor OO solutions you gave are the only way to solve the problem.

  2. One tiny, contrived example, written by a student or amateur, is not going to prove anything about anything, let alone provide a basis for such strongly stated opinions.

  3. If you want to be a better programmer, stop being a massive jerk to strangers. Most programmers aren’t talented enough to get away with it.

5

u/[deleted] May 31 '20

It was not my intention to be a massive jerk and reading it back now you're right in that it definitely sounds like an attack. I think I wrote out of emotion instead of rationality after trying FP for hours. Sorry.

2

u/reifyK Jun 03 '20

I consider these three general points of advice as canonical for that matter

11

u/gcross May 31 '20 edited May 31 '20

The point of FP is not to put every single statement of your program into its own function, it is to structure your program as much as possible in terms of transformations of pure data. In the case of your code this paradigm is not a good for fit because you are performing fairly simple manipulations of the DOM; if you were doing something complicated (or if you were using a library like React as it's based on functional programming) then it might make more sense. In fact, it isn't even clear to me what the point of declaring a class is in this context since you are just using it as a function in practice and if you are just creating a single button then even creating a separate fiction function for just that button may be overkill.

10

u/Slackwise May 31 '20

This is really missing the mark. If you're going to do this "Functionally" in JS, you'd probably just write this:

const button = label => {
  let button = document.createElement('button');
  button.appendChild(document.createTextNode(label));
  return button;
}

document.body.append(button("Click Me!"));

Although your example is DOM manipulation, or world state mutation, which is inherently not what you'd use Functional code for. There's nothing inherently wrong with mixing styles as long as you use them in the correct context for their benefit. Look into "Functional Core, Imperative Shell".

P.S. Lose the attitude, kid, it won't net you any favors.

7

u/watsreddit May 31 '20

None of those functions are pure. They all are performing side effects: interacting with the document. A pure function is something like const add = (x, y) => x + y.

So if pure functions aren't used for interacting with the DOM, what are they used for? They're for the core business logic of your application. In FP languages, we often architect applications using a "functional core, imperative shell" approach, where stuff like interaction with the user or networks calls are pushed to the edges of the application, and send off their data to pure functions for processing. This video by Gary Bernhardt does a great job of explaining the idea (it's Ruby, but you should get the gist).

If you're interested in a more functional approach to interacting with the DOM itself (though still not using pure functions, mind you), that's typically what people use React for. Here's your example as a React functional component:

const Button = ({ label, onClick }) => {
  return <button onClick={onClick}>{label}</button>
}

//Usage, in some other JSX
<Button label="Click me!" onClick={e => console.log("Clicked")} />

I also think you're conflating OOP with imperative programming. You're not really using any OOP in your "OOP example" other than sticking the imperative code in a constructor. It has no methods, member fields, etc.

I think you're approaching FP with a level of vitriol that is only going to hinder any attempts to learn it. You have to be open to new ways of thinking about programming in general if you want to develop a true understanding of the paradigm. There's a whole world there and you've only just barely scratched the surface.

1

u/toggafneknurd Jun 30 '20

You stringed together a horrifically bad strawman here. If you want to see an actual elegant manifestation of dom manipulation in a functional manner, check out reactjs.com