- Learning Functional Programming in Go
- Lex Sheehan
- 190字
- 2021-07-02 23:13:49
Dependency inversion principle
The dependency inversion principle (DIP) states that we should depend upon abstractions, not concretions. DIP is about removing hardwired dependencies from our code.
For example, the following code violates DIP:
import "theirpkg"
func MyFunction(t *theirpkg.AType)
func MyOtherFunction(i theirpkg.AnInterface)
The MyOtherFunction function is not quite as bad as the MyFunction function, but both implementations couple our implementation with a type and an interface of another package.
In general, good software design relies on high cohesion, where we write functions that do one thing and do it well and are loosely coupled.
In pure functional programming, dependency injection is accomplished by passing partially applied functions around. Some call it the hollywood principle, as in, Don't call us, we'll call you. In JavaScript, this is frequently accomplished using callbacks.
Note that there is a subtle difference between callbacks and continuations. Callback functions may be called multiple times in the flow of an application and each time they return a result and processing continues. When a function calls another function as the last thing it does then the second function is called a continuation of the first.