4 ms·
Classes, Complexity, and Functional Programming
- Terr_ 9y ago> This is how things would look if we used pure functions: My gut reaction: "Eeeewwww, procedural functions in a global namespace." I've dealt with an old codebase made that way, passing around and modifying associative arrays in lieu of real objects. (PHP, but the same principles apply.) Things get very messy very quickly, and there's no consistent/reliable way to know how a given key-value-spaghetti ought to look... except by reverse-engineering every step in the process that kept mutating it. You get the fun of manually verifying that none of those hundreds of "modify the thing" methods happened to get called with your unstructured untyped thing. > So, if `this` adds so much complexity (as I’m asserting), how do we avoid it without adding even more complexity to our code? If you want classy Javascript, you change how you define and instantiate things. Once you've defined the properties and methods of `Person`, you want you pass it through a step that transparently replaces all the methods with a wrapper that maintains the correct `this`. In essence, you automate the use of `Function.bind()`. Several frameworks provide versions of the same basic approach.
- deleted 9y ago[deleted]
- haburka 9y agoI have coded somewhat like this before, where my methods were mostly static. It feels good, but it really didn't give any return in the sense of making my code less complex or easier to test. Generally it's actually very easy to test a method that isn't purely functional, due to simple object creation during the testing process. As far as complexity, it just meant that I would make the first argument of the function the object that I was modifying. So basically, the function might as well have known about this in the first place. Eventually I just moved back to class syntax and I didn't miss it. I honestly don't understand how to do JavaScript in a purely functional way. The nature of the beast is that user input modifies data, which results in changes in state. To me, that's a contradiction of the functional paradigm, and it is better to be functional when you can and otherwise just be explicitly stateful.