Separate the Pure Code from the Impure Code
Explore how to apply functional programming principles in Elixir by separating pure code from impure operations when working with Ecto. Understand how to use pure functions for changesets and queries while isolating side effects in Repo calls. Gain techniques to streamline testing by avoiding unnecessary database interactions and improve code organization using context modules for impure functions.
Key principle of functional programming
A key functional programming principle is to write as much of the code as possible as pure functions and move the impure code with side effects to the edges of the system. This comes up often when working with Ecto, as database operations are the very definition of impure.
Repository pattern
Fortunately for us, Ecto’s Repository Pattern implementation supports this goal. Changesets, queries, and multis are pure data structures that describe impure actions against the database, but these actions don’t occur until we run them through the functions provided by Repo. This creates a clear distinction between code with side effects and code without side effects. If we’re manipulating the data structures ...