by throwaway7645 · 9y ago · 0 comments
FP => I'll have a Sazerac
Imperative => Excuse me sir, could you take some ice, add rye whiskey, add bitters, add absinthe, shake, strain into a glass, and add a lemon garnish before bringing it to me
Would you mind actually making Sazerac in your FP "analogy" as well?
(-> {}
ice
(rye :2-fingers)
bitters
absinthe
shake
strain
garnish)
Now I think that strain flipped the returned type from drink to a glass with the drink.All this shows is that OO and FP are duals [1]. I don't claim to get FP perfectly, but my moment of zen was realizing this.
The value for FP comes from proper abstraction over these processes in functional terms, at which point they can be trivially implemented (few bugs, few iteration cycles to get right). This can probably be done for every problem space, question is at which the abstraction costs outweight the gain. Considering that FP becomes more and more mainstream it's probably more viable than thought in the past, still I imagine system-driven games or complex real-world simulations, with lots of side effects, would lose more from FP than they'd gain.
Some time ago I thought that, too, but I'm no longer convinced. Directly mutating values (OO style) feels more natural at first, but then you have trouble with side effects and order of execution matters more than it should, you start keeping snapshots of the whole state just to get a consistent world state during computation, otherwise this whole mess produces a whole class of bugs on its own. These problem drive you more and more into FP direction, and the FP style definitely does have its merits in this regard.
I think the following article articulates this very well:
"A Worst Case for Functional Programming?"
Ultimately it's the same result? The difference is when you can reuse and compose functions.
FP you start with the methods and just keep composing. With OO you start with classes and objects.
Me(Drinker)->drink( Sazerac(Cocktail) ->garnish() ->strain() ->shake() ->absinthe() ->bitters() ->whiskey() ->ice() ->glass() )
(def sazerac
(-> (mix :ice :whiskey :bitters :absinthe)
shake
strain
garnish))
(drink :me sazerac)
I never had a Sazerac. It sounds like a nice drink.Either you have an object with all of garnish(), strain() and whatnot on it, or each method returns the object to handle the next step in the chain. Either methods don't scale at all without modifying existing code.
The real difference is that function composition gives you a reusable function you can further compose while objects keep piling up methods until you're left with god objects or indirection hell.
The imperative equivalent would be:
"Give me a Sazerac!"
(imperative, hehe)
Second, that's not functional programming, that's calling a library function.
FP => I'll have a Sazerac
Imperative => Serve me a Sazerac
Imperative programming isn't devoid of abstractions; it just has different ones.