How do we create pure functions?
So far in this chapter, we have taken a look at some properties of pure functions. We have also touched on some of the advantages we can gain by writing all our functions as pure functions. Now, let’s look at some things we can do to make it easier to write pure functions.
Avoid global state
One of the ways we can facilitate writing pure functional code is by avoiding the global state in our programs. In Go, this comes down to avoiding the use of const
and var
blocks at the package level as much as possible. When you see these blocks, there’s a good chance that the program state is relied upon by some functions, thus generating either side effects or having non-deterministic program execution. While it’s not always possible to completely avoid such state variables, we should try to limit their use as much as possible. The way to prevent a function from relying on this state is by having the state pass to the function through...