Refactoring Toward Pure Functions

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (17 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing Pure Functions | TOC | Isolating Code 👉

When you have a module that’s really hard to test, refactoring as much of the logic into pure functions is the easiest way to simplify testing, if you can make it work. We’ll deep dive into an example of this in the GenServer section of Chapter 3, Testing OTP, but let’s make sure we understand the basic ideas before we move on. When code has an external dependency, it rarely acts as a straight pass-through of the values of that dependency. Most of the time, it will make a call to a dependency and then manipulate the response before returning the result of the function call. The more manipulation your code does of that data, the better a candidate it is for refactoring the logic into a pure function.

Let’s look at a visual representation of a function that both calls out to a dependency and manipulates that data before returning its response.

images/overlycomplex.png

The section of our drawing labeled “manipulate data” is code that changes the data without any external dependencies. If the code has significantly different outcomes, testing this function can be pretty painful, depending on the data returned from the dependency. Each test, for each possible way that logic can…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.