In a typical C# program, we’d have something like this:
We need to contact the “outside world” to get the time. In order to make the code testable, the time-getting functionality was extracted to an external class. There’s also an interface that makes it easy to create a mock and inject it. We end up with lots of interfaces with just one implementation - that’s not the purpose of interfaces. It brings much boiler-plate code.
We could use function-injection to achieve the same behavior:
The presented example is still a bit semi-functional. Ideally, we should
DateValidator class into a function.
Modularity in FP
In OOP, we use interfaces and their implementations that are injected whenever an interface is required.
In FP, we don’t use interfaces. The function’s signature is the interface itself. Additionally, instead of creating classes that contain some logic, FP promotes the idea of creating functions with that logic. Then, if some other component requires that logic, a delegate should be used to inform about that (instead of an interface).
Here’s a practical example:
Dependecies are not stored in any fields, they are passed as parameters to the function.
The functional approach still has decoupled components (functions). Testing should become a bit easier, creating mock functions is easier than creating mock objects.