Our great sponsors
-
dependency-injection-in-functional-programming
Shows how to utilize Dependency Injection in Functional Programming
-
WorkOS
The modern identity platform for B2B SaaS. The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
In this article we’ll show you how OOP uses DI to make the classes easier to test, then we’ll show the same technique in FP using JavaScript for both implementations. Code is on Github. After reading this you’ll understand how to make your FP code easier to test and configure, just like you do in OOP style coding.
Dependency Injection is a technique for instantiating classes that conform to an interface, and then instantiating another class that needs them, and passing them into that class’ constructor. A dependency is a class that typically does some complex side effect work, such as connecting to a database, getting some data, and parsing its result. It’s also sometimes called Inversion of Control because you have a DI container manage creating all these classes and giving them to who needs them vs. you, the developer making a parent class, then hard-coding internally those composed classes; computer vs. you, dependencies are giving to class instead of class making them itself. You as the developer just give the DI container some configuration in the form of “This class needs this interface” ( a la TypeScript). In tests, the DI container will give it the stub/mock/fake implementation. When your program runs for real, the DI container will it the real/concrete implementation; same code, but different dependencies depending upon if you’re running in test mode or real mode.
Doing the equivalent functionality in Functional Programming requires a function to read the file, parse it, snag off the environment, and determine which URL to return based on that environment. We do that by making each of those steps a function, and composing them together. We’re using the Stage 2 JavaScript pipeline operator below in F# style:
This isn’t true for all functional languages, though. In Elm, for example, this technique isn’t used because Elm does not have side effects since all functions are pure. In ReScript, however, you would because while it’s Functional, it still has the exact same side effect model as JavaScript because it compiles to JavaScript.
This isn’t true for all functional languages, though. In Elm, for example, this technique isn’t used because Elm does not have side effects since all functions are pure. In ReScript, however, you would because while it’s Functional, it still has the exact same side effect model as JavaScript because it compiles to JavaScript.