Purity in my Programming Please
Tags: go, programming, tutorial
Published: 2019-10-30 17:28:59

---
title: Purity in my Programming Please
published: true
date: 2019-10-30 17:05:25 UTC
tags: golang,Programming,Tutorial,go
canonical_url: https://qvault.io/2019/10/30/purity-in-my-programming-please/
---

![](https://qvault.io/wp-content/uploads/2019/10/photo-1452199923474-9ac6f7659ec5-1024x576.jpeg)<figcaption>JK – There’s Nothing Pure About Religious Fundamentalism <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="😉" style="height: 1em; max-height: 1em;"></figcaption>

Pure functions are often hyped up in the Javascript world, probably because of the abundance of state in front end applications. While pure functions have their downsides (i.e. inconvenience, potentially large argument lists), I believe they should be used as much as reasonably possible, and I want to focus on pure functions in Go.

![](https://qvault.io/wp-content/uploads/2019/10/go.png)

## What is a Pure Function?

According to [Wikipedia](https://en.wikipedia.org/wiki/Pure_function), a Pure function has the following properties:

1. Its [return value](https://en.wikipedia.org/wiki/Return_statement) is the same for the same [arguments](https://en.wikipedia.org/wiki/Argument_of_a_function) (no variation with local [static variables](https://en.wikipedia.org/wiki/Static_variable), [non-local variables](https://en.wikipedia.org/wiki/Non-local_variable), mutable [reference arguments](https://en.wikipedia.org/wiki/Value_type_and_reference_type) or input streams from [I/O devices](https://en.wikipedia.org/wiki/Input/output)).
2. Its evaluation has no [side effects](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).

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

1. When I call a pure function I will get the same exact result every time
2. After calling a pure function my program will be in the same state it was before calling it (other than time will pass and I will have assigned the result of the function)

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
}
```

![](https://qvault.io/wp-content/uploads/2019/10/30243-200.png)<figcaption>Impure</figcaption>

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. We can assume this was done because elsewhere in the program it was a good idea to store of map of counts, but it would be better if that state management was handled outside of our counting function:

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

Much better, this function is more “pure” because it will not change the application’s state.

## 2. Database Argument

Our function 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 deterministic, 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 setup, 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.

Lets 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! Now we can have a good test:

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

And if we include how our application will likely look now including state management and the database call:

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

Thanks for reading! 

By Lane Wagner [@wagslane](https://twitter.com/wagslane)

Download Qvault: [https://qvault.io](https://qvault.io/)

Star our Github: [https://github.com/q-vault/qvault](https://github.com/q-vault/qvault)

The post [Purity in my Programming Please](https://qvault.io/2019/10/30/purity-in-my-programming-please/) appeared first on [Qvault](https://qvault.io).