# Pure functions

## Objectives :

Understand what are Pure Functions and the benefits of using them

## Connection - 10'

Categorize these code samples in ***Pure Functions*** vs ***Impure Functions*** :

```python
import random

def f(x):
    if random.randint(1, 2) == 1:
        return x + 1
    return x + 2
```

```java
public class MathUtility {
    public static int sum(int num1, int num2) {
        return num1 + num2;
    }
}
```

```java
public class Line {
    private int value = 0;

    public int add(int nextValue) {
        this.value += nextValue;
        return this.value;
    }
}
```

```java
public class MathUtility {
    private static int count = 1;
    public static int sum(int num1, int num2) {
        count++;
        multiply(num1,num2);
        return num1 + bnum2;
    }
}
```

```javascript
const double = x => x * 2;
```

Explain your choices.

## Concept - 5'

{% hint style="success" %}
Pure functions don’t refer to any global state. ***Those functions do not produce any side effects (state changes).***
{% endhint %}

They are ***easier to test because*** of these properties:

1. You can see all the inputs in the argument list
2. The execution is deterministic (the same inputs will always get the same outputs)
3. You can see all the outputs in the return value

*Code that is harder to test will lack some or all of these properties.*

## Concrete Practice - 30'

* Clone the repository [here](https://github.com/ythirion/pure-functions)
* Identify the design problems related to the RentalCalculator
* Refactor this code by using ***Pure Functions***

{% hint style="success" %}
A step by step solution is provided in the ***solution*** branch (Look at the commits)
{% endhint %}

![](https://1936518372-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MAffO8xa1ZWmgZvfeK2%2F-MT5cm4iB5V7AzDKHuDV%2F-MT5d-oaQiy6S5OUmbkR%2Fimage.png?alt=media\&token=d1467f18-bd8f-4d11-9648-a8c10ca2ae76)

## Conclusion - 10'

* How much of the time do you find yourself writing tests for functions that have all the three properties of pure functions ?
* What do you need to write more Pure Functions ?
