How to turn a script with shared state into stateless modules and pure functions?
I've been advised that I should write only pure functions and stateless modules, but I don't really know where to start. Would someone be willing to give me an example of how a base script like this could be turned into stateless modules with pure functions?
https://jsfiddle.net/r4gbdqmz/
It's quite tiny, don't worry. I would really appreciate it so I can start figuring out how to refactor the right way, thanks!
Posted Feb 6, 2018, 9:17 AM UTC
a basic attempt here https://jsfiddle.net/r4gbdqmz/14/
state should come from "above"
dependencies should be parameters for purity and statelessness
things that have "side effects" exist, but you can isolate them to keep as many pure functions as you can--see how now fewer things have access to external "shared" state?
if it's easy to write a unit test for, it's probably closer to the pure and stateless side
Thank you, I actually realized myself a couple days ago that one of the main keys to it was probably using higher-order functions like that - not that higher-order functions were a novel concept, but I never put together the idea that they're an appropriate tool for something like that.
"State should come from above" is a good phrase to remember. I had the feeling that what I heard was dogmatic for the sake of it and not to be taken entirely seriously. It's not so much that state should be avoided everywhere at all costs (if that's even possible), but that if state is necessary for non-convoluted code, it's better to contain it as much as possible, and like you say, send the state (or the necessary data in the state) as a parameter to other functions - which means it needs to start from somewhere high-up in the hierarchy.