|
|
|
Ask HN: Explain to me why functional programming is better like I'm stupid
|
|
4 points
by jagtstronaut
834 days ago
|
|
I have a coworker who really harps on functional programming. To me the block of .map(x).ifelseget().etc() is so much harder to read than defining and mutating variables, if/switch statements, and loops. Also, if you get a stack trace, the line number doesn't really tell you much if you are doing 4 things on a single line. I have always wondered this since I have been confronted with it, but in an interview recently I was given a light docking for not using functional programming. Why is it better? |
|
In functional programming everything is predictable:
input -> [some function] -> output
Where in OO things are:
input -> [some function + some hard to reason about state] -> output
In OO functions tend to be "impure" because you typically have state which can always do something you don't expect. This becomes even more problematic when you add parallelism to the mix because now state can mutate in ways that that is very hard to reason about.
With functional programming if something unexpected happens then you know that it's the function's logic rather than having to try to understand how some unexpected state is causing a function to do something you didn't expect. For this reason functional logic much easier to test and verify because the surface area for unexpected results is dramatically reduced.
That said, functional programming is much less intuitive I think. We tend to naturally reason about the world as a collection of objects with state and actions, and when an action is performed state mutates.
Functional programming requires you get rid of the idea of objects which have mutable state and instead think about the world as a collection of processes which given stateT1, spit out stateT2.
I've noticed people from a math background find the purity of functional programming very appealing. Personally I tend to share that bias, but I still recognise that functional programming isn't the best paradigm for most applications.
If you're building a simple API or app for example, then I think the most important thing is writing code that's easy to comprehend. If the domain is simple then the benefits of functional programming are relatively slim. It's really only when you're dealing with complex state and parallelism that functional programming really starts to have major benefits in my eyes. I think your observation that functional programming being harder to read is 100% correct, and this is its main trade off in my view.