# 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 %}

![](/files/-MT5d-oaQiy6S5OUmbkR)

## 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 ?


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yoan-thirion.gitbook.io/knowledge-base/software-craftsmanship/code-katas/pure-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
