5 Higher-kinded composition
This chapter covers
- The advantages of programming with immutable, composable objects
- How to map and flatMap over arrays and any object
- The basics of functors and monads
- Understanding the relationship between map and compose
- Writing a Validation Algebraic Data Type (ADT)
- Composing validated data flows via the HasValidation mixin
“The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise”
Edgar Dijkstra
In the previous chapter you learned how function composition leads to very fluent, compact, and declarative code using compose to chain your function’s inputs and outputs as data passes through them. Composition has a lot of benefits because it uses JavaScript’s strongest feature: higher-order functions. With functions you can achieve low-level composition. With the help of some simple APIs, you can achieve a higher-kinded composition.
Take a moment to reflect about some of the problems we tackled in chapter four. What would happen if the data that one function receives along the chain were invalid, null, or undefined? Syntactically speaking, when using compose you can’t insert imperative conditional validation blocks in between logic functions. Your best bet would be to move validation logic into its own function, as such: