Constructors, Reducers, and Converters
Let's get to know the role of CRC in Phoenix and Elixir modules.
We'll cover the following
Pipelines and functional composition play a big role in Elixir. One pattern called CRC plays a huge role in many different Elixir modules. Its roots are closely entwined with the common function Enum.reduce/3
. Let’s take a closer look.
Web frameworks in functional languages all use variations of a common pattern. They use data represented by a common data type and use many tiny, focused functions to change that data, step by step. For example, in the JavaScript world, the state reducer pattern by Kent Dodds uses many of the same strategies. Clojure has a similar framework called Ring.
In Phoenix, the Plug framework follows the same pattern. Let’s explore this pattern in more detail.
Plug Patterns
In Elixir, many modules are associated with a core
type. The String
module deals with strings, Enum
deals with enumerables, and so on. As often as possible, experienced Elixir developers strive to make a module’s public functions related to its core type. Constructors create a term of the core type from convenient inputs. Reducers transform a term of the core type to another term of that type. Converters convert the core type to some other type. Taken together, we’ll call this pattern CRC
.
So far, CRC might seem abstract, so let’s take a simple, tangible example.
We built a module that has one of each of these functions. Test it by firing up the IEx in the terminal below:
Get hands-on with 1400+ tech skills courses.