Functors for dependency injection?

testing

#1

Hi, so I’m quite familiar with dependency injection in object-oriented languages such as Java and JavaScript.

I’ve been doing some reading about DI in FP, and Ch. 9 of RWO v1 states that functors can solve dependency injection. I have also found an article that perfectly illustrates this, and I can see the pattern there.

I want to ask, how common is this used in practice? Does dependency injection in FP a thing at all (or am I approaching this the wrong way)? How do OCaml devs test modules that interact with other modules/libraries (which are probably impure) in isolation?

I am also aware that you can write your functions accepting the dependency functions as arguments and utilize currying. Is this pattern more reasonable?

If there are projects that make use of either approach for DI and testing, I would love to be pointed to it.


#2

Functors, high order functions and parametric polymorphism are used in functional programming to achieve this kind of abstraction. But so far, I have never heard anyone refer to it as dependency injection. I think that phrase if more relevant to object oriented thinking.


#3

I think the technique is used in Mirage, I remember @avsm talking about it in a podcast: they have signatures that specify operations like I/O, and implement them for different target platforms: Xen, Unix, etc.


#4

Yeah it might be true, but seems like that’s not too far off? e.g. if module A calls module B then module B is a dependency of A, and using functor we can “inject” B to A instead of it being a direct call… nevertheless, I’m glad to hear that those techniques are common.

Thanks! I also end up checking out the Irmin project that seems to utiilize functor for that. Could you point me to the mentioned podcast?


#5

Sure: https://twit.tv/shows/floss-weekly/episodes/302


#6

In OOP, because mutable state and functions that act on that state are bound together, it’s much harder to test them reliably. Just switching to immutable state and functions already makes it easier to test your code, without any need for dependency injection. You don’t get the complexity buildup that mutable state causes.

For mutable state that does exist in your programs, functors are good, as are first-class modules. In fact, OCaml is almost ideally suited for this due to its obsession with abstraction of types. I would venture though that many programmers making heavy use of FP don’t deal with a lot of state. Most of this kind of thing happens in large companies or specific organizations (such as Mirage), resulting in the fact that DI isn’t commonly discussed in the FP world.