Wednesday, 3 August 2016

Destroy All Ifs — A Perspective from Functional Programming – John A De Goes

Destroy All Ifs — A Perspective from Functional Programming – John A De Goes:



"I’ve long argued that, despite all its flaws, one of the great things about functional programming is its intrinsic inversion of control.
In an impure imperative language, if you call some function void doX(State *state), the function can do anything it wants. It can modify state (both passed in and global), it can delete files, it can read from the network, and it can even launch nukes!



In a pure functional language, however, if you call some function doX :: State -> IO (), then at most it’s going to return a value. It can’t modify what you pass it, and if you like, you can ignore the value returned by the function, in which case calling the function has no effect (aside from sucking up a little CPU and RAM).



Now granted, IO in Haskell is not a strong example of an abstraction that has superior reasoning properties, but the fundamental principle is sound: in pure functional programming languages, the control is inverted to the caller.
Thus, as you’re looking at the code, you have a clearer sense of what the functions you are calling can do, without having to unearth their foundations.



 I think this generalizes to the following principle:
Code that inverts control to the caller is generally easier to understand.
(I actually think this is a specialization of an even deeper principle — that code which destroys information is generally harder to reason about than code which does not.)



Viewed from this angle, you can see that if we embed conditionals deep into functions, and we call those functions, we have lost a certain amount of control: we feed in inputs, but they are combined in arbitrary and unknown ways to arrive at a decision (which code path to take) that has humongous ramifications on how the program behaves.
It’s no wonder that conditionals (and with them, booleans) are so widely despised!



 In an object-oriented programming language, it’s generally considered a good practice to replace conditionals with polymorphism.
In a similar fashion, in functional programming, it’s often considered good practice to replace boolean values with algebraic data types."



'via Blog this'

No comments:

Post a Comment