DEV Community

Discussion on: Dependency injection in functional programming

 
psfeng profile image
Pin-Sho Feng

DI refers to dependency injection, which is basically passing a dependency as a parameter to a function instead of having the function call it directly. For example:

fun doSomething() {
    fetchItemsFrom("http://someurl.com/items") // this is hardcoding the URL that you want to use
}

fun doSomething(url: String) {
    fetchItemsFrom(url) // now url is "injected" to the function.
} 

fun doSomething(fetchItems: () -> Unit) {
    fetchItems() // you can also choose to pass the whole function
}

DI and mocking for testing are related in that you can pass mocks (or stubs) to the function under test. If what you're injecting is a side-effectful function, you can indeed replace it with some mock function that doesn't have side-effects, just for the purposes of testing.

Let me know if it's clearer now!

Thread Thread
 
koresar profile image
Vasyl Boroviak

The only difference I see is that with DI the replaced value can be data.

Sorry. I still believe DI and ability to mock is the same concept - ability to replace a thing down the call chain.

Thread Thread
 
psfeng profile image
Pin-Sho Feng

Dependency injection is a concept and the ability to mock is a consequence of this concept, but it's by no means the only benefit.

You could, for example, use some class across different sections of an app but have it behave differently depending on the section. Using the dependency injector you can configure the different instances of the class that will be used in each section.