3 ms·
State is unavoidable. But FP, rather than being just another cargo cult is simply a different approach to programming. In a nutshell: imperative languages arriv
by jacquesm 3y ago
State is unavoidable. But FP, rather than being just another cargo cult is simply a different approach to programming. In a nutshell: imperative languages arrive at a castle through piling stones on top of each other until they have the shape of the castle, and functional languages transform a pile of stones into a castle. The difference is subtle: the one is about how you do the work, the other is about the end result. There are several major consequences from using the one or the other technique and both have their advantages and disadvantages. FP is probably easier for people with a math background and imperative programming is probably easier for people that look at programming in the same way that you'd look at building something out of real world components.
State, that big bad thing is something that is unavoidable in programming because at some level you will have state and side effects. But the longer you can put off having state (preferably all the way to the top) the cleaner your code will be and the easier it will be to test. That is because state effectively complicates the number of dimensions that your test has to verify against. If there are 5 variables of state and 5 function parameters that may still be doable. But if your execution context contains 500 variables and your function takes 5 parameters you now have to test against all of the permutations of 505 elements to ensure your function does what it should do. And if your function is going to modify that state (rather than return a result) it gets even worse for every function that calls this one.
So functional programming helps in the same way that processes can encapsulate a certain amount of functionality within a limited scope: the scope of a function that has no side effects (so it does not modify the state of the program) and that does not look at anything other than its parameters is very well defined, if it works once with a certain set of parameters it will always do so with those parameters. So now you can write some pretty clean and simple test cases to verify this function once and for all and if it passes the tests you are able to make some guarantees about it.
This can turn your worldview of programming upside down, it is a very powerful technique and to suggest it is 'cargo cult' is potentially throwing out a very powerful tool.
hth