January 15th, 2018
Filed under: iOS Development, Mac Development | 2 comments
A pure function doesn’t reference any data outside of the function. If you supply a given input to a pure function, it always returns the same value. The following is a simple example of a pure function:
func increment(value: Int) -> Int {
return value + 1
}
The increment
function is pure because it increments the value you supply to it. It doesn’t modify any outside variables. If you pass the value 9 to increment
, it always returns 10.
The following code is a hypothetical example of an impure function that updates contact information based on the values of text fields in an app’s user interface:
func updateContactInfo() {
name = nameTextField.text
address = addressTextField.text
phone = phoneTextField.text
}
The updateContactInfo
function is impure because it modifies variables outside of the function: name
, address
, and phone
.
A big advantage of pure functions is they’re much easier to unit test. To test the increment
function, all you have to do is create an integer, call increment
, and assert the incremented value is correct.
I know increment
is a simple function, but unit testing any pure function follows the same steps.
Unit testing the updateContactInfo
function would be painful. You would have to perform the following steps:
updateContactInfo
.Tags: functional programming, swift
Hey,
Did you figure out how to approach pure functions that are composed of other pure functions? Unit testing each of them is simple, but testing the composite itself isn’t. (Unless you inject the parts as closures, which is kind of odd.)
Cheers,
Christian
Christian,
I haven’t figured that out yet. Maybe someone else reading this post will have an answer for you.