Separate the Pure Code from the Impure Code
Learn how to separate the pure code from the impure code.
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 Ecto provides (for example, building up a changeset), we can consider that code “pure.” As soon as the Repo is involved, the code is likely to have side effects and should be considered “impure.”
A benefit: Streamlining of tests
One benefit of this arrangement is that it helps us streamline our tests. Consider the following test case, which verifies that our Album
module generates the correct changeset (we added a changeset
function to the Album
module back here—we’ll need to do that for this test to work if we haven’t already).
Get hands-on with 1400+ tech skills courses.