How to Make Pure Functions (Go)

Pure Functions in Go

The post How to Make Pure Functions (Go) first appeared on Qvault.

Pure functions are often hyped up in the JavaScript world, probably because of the abundance of stateful front end applications. While pure functions have their downsides (i.e. inconvenience, potentially large argument lists), they should be used as much as reasonably possible.

We’ve made a lot of changes in the Qvault app codebase recently to use more pure functions, and it has helped make the code easier to understand and write tests for.

What is a Pure Function?

According to Wikipedia, a Pure function has the following properties:

  1. Its return value is the always same for the same arguments
  2. Its evaluation has no side effects (no mutation of data outside the function)

Which means that as a developer I know two important things:

  1. When I call a pure function I will get the same result every time
  2. After calling a pure function the rest of my program will be in the same state it was before calling it

Because of these properties, pure functions keep applications simple. As we know, simple applications tend to be faster, are easier to test and debug, and are less error prone in general.

Example in Go (golang)

totalCounted := map[string]int{}

func countNamesInText(text string) {
        total := 0
        const name = getNameFromDatabase()
        for _, word := range strings.Split(text, " ") {
                if word == mention {
                        total++
                }
        }
        totalCounted[name] = total
}

This function is impure for a couple reasons. Let’s examine each one.

1. Program state is mutated by calling countNamesInText()

Instead of mutating a global variable as a means of “returning” data to the caller, we should return the data via a return statement:

func countNamesInText(text string) int {
        totalCounted := 0
        const name = getNameFromDatabase()
        for _, word := range strings.Split(text, " ") {
                if word == mention {
                        totalCounted++
                }
        }
        return totalCounted
}

Now countNamesInText is more “pure” because it will not change the application’s state, though you may have noticed that we still have another problem.

2. Database Argument

countNamesInText is still impure because the “name” value, which affects the result of the function call, is retrieved from a database. In order for our function to be self-contained, that value should instead be passed as a parameter.

Currently, if we wrote the test:

func TestCountNamesInText(t *testing.T) {
        assert.Equal(t, 2, countNamesInText("this word here"))
}

It wouldn’t work consistently. If the database isn’t set up, or if the database was tampered with, our tests will fail. That makes this a bad test, and we wrote the bad test because we have an impure function.

Let’s purify a bit more:

func countNamesInText(text, name string) int {
        totalCounted := 0
        for _, word := range strings.Split(text, " ") {
                if word == mention {
                        totalCounted++
                }
        }
        return totalCounted
}

Our function is pure, so we can write a good test:

func TestCountNamesInText(t *testing.T) {
        assert.Equal(t, 1, countNamesInText("this word here", "this"))
}

This is what a call to the function in the application might look like:

totalCounted := map[string]int{}
name := getNameFromDatabase()
totalCounted[name] = countNamesInText("some name in here", name)

Thanks For Reading!

Follow us on Twitter @q_vault if you have any questions or comments

Take some coding courses on our new platform

Subscribe to our Newsletter for more programming articles

Related Articles



source https://qvault.io/2020/09/07/purity-in-my-programming-please/

Comments

Popular posts from this blog

Why is Exclusive Or (XOR) Important in Cryptography?

What are UUIDs, and should you use them?

6 Things to Avoid When Contributing to Open-Source Projects