▲ | maxbond 10 months ago | |
You've got the gist of it. By decoupling your function from the state of your application, you can test that function in isolation. For instance, you might be tempted to write a function that opens an HTTP connection, performs an API call, parses the result, and returns it. But you'll have a really hard time testing that function. If you decompose it into several tiny functions (one that opens a connection, one that accepts an open connection and performs the call, and one that parses the result), you'll have a much easier time testing it. (This clicked for me when I wrote code as I've described, wrote tests for it, and later found several bugs. I realized my tests did nothing and failed to catch my bugs, because the code I'd written was impossible to test. In general, side effects and global state are the enemies of testability.) You end up with functions that take a lot of arguments (10+), which can feel wrong at first, but it's worth it, and IDEs help enormously. This pattern is called dependency injection. https://en.wikipedia.org/wiki/Dependency_injection See also, the "functional core, imperative shell" pattern. |