In this chapter you will learn
-
why we need pure functions
-
how to pass copies of the data
-
how to recalculate instead of storing
-
how to pass the state
-
how to test pure functions
“ Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function. ”
—John Carmack
Why do we need pure functions?
In the last chapter we learned about functions that don’t lie. Their signatures tell the whole story about their body. We concluded that these are the functions we can trust : the fewer surprises there are when we code, the fewer bugs there will be in the applications we create. In this chapter we will learn about the most trustworthy of all the functions that don’t lie: a pure function .
THIS IS BIG!
Pure functions are the foundation of functional programming.
Shopping cart discounts
Let’s start by looking at an example that doesn’t use pure functions. We’ll go through its problems and try to solve them intuitively first. Our task is to write a “shopping cart functionality” that is able to calculate discounts based on the current cart contents .
Requirements: Shopping cart
-
Any item (modeled as a String ) can be added to the cart.
-
If any book has been added to the cart, the discount is 5%.
-
If no book has been added, the discount is 0%.
-
Items in the cart can be accessed at any time.
We can design a solution that is a direct encoding of the requirements above. Here’s a diagram of the ShoppingCart class responsible for handling them:
Note that we sometimes omit types and other details in drawings to make them as clear as possible. Here, we omitted the String type in the addItem parameter list.
Before we dive into the implementation and real code, let’s briefly go through the diagram above. The ShoppingCart class has two fields, items and bookAdded , which are used as an internal state. Then, each requirement is implemented as a single method. The three methods are being used as a public interface by the rest of the world (class clients).
Coding imperatively
We designed a solution for our problem by coming up with some state fields and public interface methods. Warning! The design of ShoppingCart has some very serious problems! We will discuss them shortly. If you have already spotted them, good for you! If not, please keep thinking about all the possible ways this design and the code below may be misused.
Now, it’s time to write some code.
public class ShoppingCart {
private List<String> items = new ArrayList<>();
private boolean bookAdded = false;
public void addItem(String item) {
items.add(item);
if(item.equals("Book")) {
bookAdded = true;
}
}
public int getDiscountPercentage() {
if(bookAdded) {
return 5;
} else {
return 0;
}
}
public List<String> getItems() {
return items;
}
}
Here’s the diagram that represents the code snippet at the bottom of the page. The gray area represents state (i.e., variables that will change over time).
Remember that this is only a small example, which aims to showcase some non-obvious problems that do exist in real codebases and are much harder to detect.
Looks reasonable, right? If a book is added to the cart, we set the bookAdded flag to true . This in turn is used in getDiscountPercentage to return the proper discount percentage. Both items and bookAdded are called state because these values change over time. Now, let’s look at how we could use this class.
ShoppingCart cart = new ShoppingCart();
cart.addItem("Apple");
System.out.println(cart.getDiscountPercentage());
console output: 0
cart.addItem("Book");
System.out.println(cart.getDiscountPercentage());
console output: 5
Breaking the code
Even though all the code we’ve seen so far looks good, the implementation of the ShoppingCart class is still incorrect. And this has a lot to do with the state : items and bookAdded fields. Let’s look at one possible flow in the program to see this problem.
class ShoppingCart {
private List items = new ArrayList<>();
private boolean bookAdded = false;
public void addItem(String item) {
items.add(item);
if(item.equals("Book")) {
bookAdded = true;
}
}
public int getDiscountPercentage() {
if(bookAdded) {
return 5;
} else {
return 0;
}
}
public List getItems() {
return items;
}
}
Yes, we didn’t plan for this kind of usage of getItems , but remember that if it is possible, it will most likely be used by someone in the future. When programming, we need to think about all the possible usages to confirm we guard the internal state the best we can. | |
After removing the book directly from the list, we create a state that is corrupted: there is no book in the cart, but getDiscountPercentage() returns 5 . This problematic outcome arises because the state is handled improperly .
By the way, using get I tems().add would also cause problems! Experienced developers may be quick to disregard this example as an obvious code smell, but rest assured that such problems happen quite often!
Passing copies of the data
The problem we hit in the previous example can easily be fixed by returning a copy of the List when somebody calls getItems .
public class ShoppingCart {
private List items = new ArrayList<>();
private boolean bookAdded = false;
public void addItem(String item) {
items.add(item);
if(item.equals("Book")) {
bookAdded = true;
}
}
public int getDiscountPercentage() {
if(bookAdded) {
return 5;
} else {
return 0;
}
}
public List<String> getItems() {
return items;
}
}
We are not returning the current items state but making a copy and returning it instead. This way nobody will be able to corrupt it.
public List<String> getItems() {
return new ArrayList<>(items); ①
}
① We will explain why we are using copies instead of Collections . unmodifiableList in chapter 3.
This may not seem like a big change but passing copies of data is one of the fundamental things done in functional programming ! We will cover this technique in depth very soon. But first, we need to make sure the whole ShoppingCart class is correct—no matter how it’s used.
Removing an item
Let’s assume a client of our class, surprisingly, needs an additional functionality that was not specified at the beginning. We learned about it the hard way when our code misbehaved. Here’s requirement #5:
5. Any item previously added to the cart can be removed.
THIS IS BIG!
We pass copies of data in FP instead of changing the data in place.
Since we are now returning a copy of items , to satisfy this requirement we need to add another public method:
public void removeItem(String item) {
items.remove(item);
if(item.equals("Book")) {
bookAdded = false;
}
}
Is this the end of our problems? Is the code correct now? | |
Breaking the code . . . again
We started returning a copy of items and added the removeItem method, which improved our solution a lot. Can we call it a day? It turns out we can’t. Surprisingly, there are even more problems with ShoppingCart and its internal state than one might have anticipated. Let’s look at another possible flow in the program to see a new problem.
class ShoppingCart {
private List<String> items = new ArrayList<>();
private boolean bookAdded = false;
public void addItem(String item) {
items.add(item);
if(item.equals("Book")) {
bookAdded = true;
}
}
public int getDiscountPercentage() {
if(bookAdded) {
return 5;
} else {
return 0;
}
}
public List<String> getItems() {
return new ArrayList<>(items);
}
public void removeItem(String item) {
items.remove(item);
if(item.equals("Book")) {
bookAdded = false;
}
}
}
We added two books and removed only one of them. That’s how we created a state that is corrupted: there is a book in the cart, but getDiscountPercentage() returns 0 ! This problematic outcome arises because, again, the state is handled improperly .
Recalculating instead of storing
The problem we hit in the previous example can be fixed by taking a step back and rethinking our main objective.
We were tasked with creating a shopping cart functionality that is able to calculate a discount. We trapped ourselves by trying to keep track of all the additions and removals and imperatively deciding whether a book has been added or not. Instead, we could just recalculate the discount every time it’s needed by going through the whole list.
What a change! Our code is much safer and less problematic now. All the logic related to discounts is now in getDiscountPercentage . We don’t have the bookAdded state, which caused us so many problems. The only downside of this change is that for very large shopping lists, the discount may take a long time to calculate. We are trading corner-case performance for readability and maintainability. *
* We will come back to this topic in chapter 3.
Focusing on the logic by passing the state
Let’s look at the final solution and think a bit about what it really does.
class ShoppingCart {
private List<String> items = new ArrayList<>(); ①
public void addItem(String item) { ②
items.add(item);
}
public int getDiscountPercentage() { ③
if(items.contains("Book")) {
return 5;
} else {
return 0;
}
}
public List<String> getItems() {
return new ArrayList<>(items); ④
}
public void removeItem(String item) { ⑤
items.remove(item);
}
}
① items is our internal state that we need to tiptoe around.
② addItem is just a wrapper around List ’s add method.
③ This function is the only original one. It fulfills our requirements.
④ getItems is just a wrapper that we need to guard the List by always returning its copy.
⑤ removeItem is just a wrapper around List ’s remove method.
The problem with the solution above is that we need lots of boilerplate code to make sure the state can’t be accessed outside of the class. At the same time the most important function, from the business-requirements perspective, is getDiscountPercentage . In fact, this is the only functionality that’s needed!
We can get rid of all the wrapper functions around items by requiring it to be passed as an argument.
class ShoppingCart {
public static int getDiscountPercentage(List<String> items) {
if(items.contains("Book")) {
return 5;
} else {
return 0;
}
}
}
We use the static keyword to indicate that the function doesn’t need any instance to be useful. | |
And this is the functional solution to this problem .
Where did the state go?
You are probably worried about the latest change in the ShoppingCart class. How can we just remove all the state and leave one function there? What about the remaining requirements? The three below are still not satisfied by getDiscountPercentage in its current form: | |
-
Any item (modeled as a String ) can be added to the cart.
-
Items in the cart can be accessed at any time.
-
Any item previously added to the cart can be removed.
However, when you look closer, these requirements can be satisfied by any list-like class! And there are plenty to choose from in the standard library. Even if we didn’t have any in the standard library, we could write our own that doesn’t know anything about discounts.
List<String> items = new ArrayList<>();
items.add("Apple");
System.out.println(ShoppingCart.getDiscountPercentage(items));
console output: 0
items.add("Book");
System.out.println(ShoppingCart.getDiscountPercentage(items));
console output: 5
As you see, we don’t have any state, we just pass a list of items to our discount-calculation function. We still have all the powers we had before, but now we have less code!
Separation of concerns *
We split the requirements into two separate sets that are fulfilled by different pieces of code! This way we have smaller, independent functions and classes, which means they are easier to read and write. In software engineering, this is called a separation of concerns : every piece of code has its own responsibility and is concerned only about it. To see it in action, let’s go through all the requirements and see how they are fulfilled.
THIS IS BIG!
In FP, we separate concerns into different functions.
As you can see, all state handling is now done in the ArrayList class .
* We will spend more time on this topic later in the book, particularly in chapters 8 and 11.
The difference between impure and pure functions
We’ve come a long way from an imperative to a fully functional solution. Along the way, we fixed some bugs and discovered some patterns. It’s about time to list those patterns and, finally, meet the protagonist of this chapter. It turns out that the latest version of the getDiscountPercentage function has all the characteristics of a pure function .
Imperative | Functional |
class ShoppingCart { private List<String> items = new ArrayList<>();
private boolean bookAdded = false;
public void addItem(String item) {
items.add(item);
if(item.equals("Book")) {
bookAdded = true;
}
} Function doesn't return a value
Function mutates existing values
| class ShoppingCart {
public static int getDiscountPercentage(List items) {
if(items.contains("Book")) {
return 5;
} else {
return 0;
}
}
}
Function always returns a single value
Function calculates the return value based only on its arguments
|
public int getDiscountPercentage() {
if(bookAdded) {
return 5;
} else {
return 0;
}
} Function calculates the return value based on more than just arguments
| |
public List getItems() {
return items;
}
} Function calculates the return value based on more than just arguments
| Function doesn't mutate any existing values
|
THIS IS BIG!
We use three rules to create pure functions, which are less buggy.
On the left side you can see the imperative solution we started with. It looked quite OK, but then we analyzed it more deeply and found some problems. We intuitively solved those problems and accidentally ended up with a class with a single static function (on the right).
Then, we analyzed the differences between those functions. We noticed three characteristics that the functional `ShoppingCart` has, which are missing in the imperative `ShoppingCart` class. **These are the main rules we should all follow when programming functionally.** We don’t really need intuition to solve our problems. Following these rules alone will highlight problems in our code and suggest refactorings. We will discuss this deeply very soon, but first I will let you use these three rules to do a refactoring of your own.
## Coffee break: Refactoring to a pure function 
Now it’s your turn to refactor imperative code into a pure function, but in a totally different piece of code. You are going to refactor the `TipCalculator` class that can be used by a group of friends to calculate a tip based on the amount of people involved. The tip is 10% if the number of people splitting the bill is from one to five. If a group is larger than five people, the tip is 20%. We also cover the corner case of dining and dashing—when there are no people, then the tip is obviously 0%.
Here’s the code. **Your task is to refactor the class below, so each function satisfies the three rules of a pure function** .
```typescript
class TipCalculator {
private List
names = new ArrayList<>();
private int tipPercentage = 0;
public void addPerson(String name) {
names.add(name);
if(names.size() > 5) {
tipPercentage = 20;
} else if(names.size() > 0) {
tipPercentage = 10;
}
}
public List getNames() {
return names;
}
public int getTipPercentage() {
return tipPercentage;
}
}
```
Rules of a pure function
1. Function always returns a single value.
2. Function calculates the return value based only on its arguments.
3. Function doesn’t mutate any existing values.
Remember the three techniques we learned about: _recalculating instead of storing_ , _passing the state as an argument_ , and _passing copies of data_ .
## Coffee break explained: Refactoring to a pure function 
It looks like the `TipCalculator` class suffers from some problems we are very familiar with. We know exactly what we should do.
First, let’s see which rules are broken by functions in `TipCalculator` .
```typescript
class TipCalculator {
private List names = new ArrayList<>();
private int tipPercentage = 0;
public void addPerson(String name) { ①
names.add(name);
if(names.size() > 5) {
tipPercentage = 20;
} else if(names.size() > 0) {
tipPercentage = 10; ②
}
}
public List getNames() { ③
return names;
}
public int getTipPercentage() { ④
return tipPercentage;
}
}
```
① `addPerson` doesn’t return any value. A pure function should always return a single value.
② `addPerson` mutates existing values: `names` and `tipPercentage` . A pure function should never mutate any values, it can only create new ones.
③ `getNames` calculates its return value based on the external state (the `names` variable). A pure function should only use arguments to create the return value.
④ `getTipPercentage` calculates its return value based on the external state (the `tipPercentage` variable). A pure function should only use arguments to create the return value.
Recalculating instead of storing
Let’s fix `getTipPercentage` first. It calculates its value based on the `tipPercentage` field, which is an external variable and not passed as an argument. The `tipPercentage` field is calculated and stored by the `addPerson` function. To fix the `getTipPercentage` function, we will need to use two techniques. The first one is **recalculating instead of storing** .
```
public int getTipPercentage() { ①
if(names.size() > 5) {
return 20;
} else if(names.size() > 0) {
return 10;
}
return 0;
}
```
① `getTipPercentage` still calculates its return value based on an external state, but we are one step closer to making it pure.
Passing state as an argument
The getTipPercentage function calculates a discount instead of using the stored value, but it still uses the external names value to do the calculation. We need to pass the state as an argument and make the getTipPercentage function pure. Others, however, are still not pure. | |
```typescript
class TipCalculator {
private List names = new ArrayList<>();
public void addPerson(String name) { ①
names.add(name); ②
}
public List getNames() { ③
return names;
}
public static int getTipPercentage(List names) {
if(names.size() > 5) {
return 20;
} else if(names.size() > 0) {
return 10; ④
}
}
```
① `addPerson` still doesn’t return any value.
② `addPerson` mutates an existing value: `names` .
③ `getNames` calculates its return value based on the external state.
④ Since this function is pure, it only uses arguments to calculate the return value. It now recalculates the tip each time `getTipPercentage` is called with the current list of names. It is much safer than the original version. We don’t have an additional moving part of mutable state, and we can reason about `getTipPercentage` in isolation.
Passing copies of data
To fix `addPerson` , we need it to stop mutating any existing values and start **returning** modified **copies** as return values.
```typescript
class TipCalculator {
public List addPerson(List names, ①
String name) {
List updated = new ArrayList<>(names);
updated.add(name);
return updated;
}
public static int getTipPercentage(List names) {
if(names.size() > 5) {
return 20;
} else if(names.size() > 0) {
return 10;
} else return 0;
}
}
```
① `addPerson` is now a pure function because it doesn’t mutate any existing values. However, we can also just remove it because it’s only a wrapper around the `add` method of `ArrayList` .
Note that we specifically asked to refactor three functions. However, we slightly changed the API in the process and ended up with two (or just one?) functions. This is how pure function rules can guide us to better and safer APIs!
And that’s a wrap! We transformed imperative functions into pure ones just by following the three rules. Our code is now easier to comprehend and therefore more maintainable.
## In pure functions we trust
We started this chapter by going through a real-world example that had tricky bugs. We were able to refactor it into a pure function by following three simple rules. It goes without saying that we could also fix the bugs using an imperative approach. However, the point here is that programmers tend to create fewer bugs just by trying to write pure functions than when they follow the requirements and directly encode them as classes and methods.
We say that pure functions are “easy to reason about.” We don’t have to build large models of state transitions in our brains to understand them. Everything a function can do is right there in its signature. It takes some arguments and returns a value. Nothing else matters.
THIS IS BIG!
Pure functions are the foundation of functional programming.
Mathematical functions are pure
Pure functions ’ existence in programming is inspired by mathematical functions, which are always pure. Let’s say we need calculate the final price of a discounted item we want to buy. The discount is 5%. We get our calculator out and input the price, $20, then press `*` , then `95` (100% - 5%) and then we get rid of percentages by pressing `/ 100` . After pressing `=` , we get our final price: $19. What we just did, mathematically speaking, is
```
f(x) = x * 95 / 100 ①
```
① If the price is $20, we will pay only $19 after the discount! Pretty cool!
For any given price `x` , the function `f` above will give us a discounted price back. So, if we give 20, 100, or 10 as `x` , calling `f` will give us the correct answers:
```
f(20) = 19
f(100) = 95
f(10) = 9.5
```
`f` is a pure function because it has three important characteristics:
- It always returns a single value.
- It calculates the return value based only on its arguments.
- It doesn’t mutate any existing values.
These three characteristics are the main focus of this chapter. We have already applied them in our real programming tasks and seen that we can trust more in our code if it’s built in a pure way.
Now, it’s time to discuss the characteristics and rules of a pure function in depth. We’ll learn how to detect pure functions and what programming language primitives are needed to write them.
## Pure functions in programming languages
This is the pure mathematical function that calculates a discounted price:
| 
| Math | Both snippets do the same thing: they calculate 95% of a given value. |
It can be easily translated to Java: | |
static double f(double x) { return x * 95.0 / 100.0;
} | Java |
Most importantly, nothing was lost in translation. This function, written in Java, still has the three characteristics of the pure function.
It returns only a single value
The Java version of the function, as its mathematical counterpart, exists to do one thing and one thing only: it always returns exactly one value.
Note that a list is also a single value, although it can hold multiple values inside. That’s OK! The main point here is that a function always returns a value.
It calculates the return value based on its arguments
The Java version of the function, exactly like the math version, takes one argument and calculates the result based solely on this argument. Nothing more is used by the function.
It doesn’t mutate any existing values
Both the Java and math versions of the function don’t change anything in their environment. They don’t mutate any existing values, and they don’t use nor change any state fields. We can call them many times, and we will get the same result when we provide the same list of arguments. No surprises!
Pure function
More generally, we say that a function is pure if
- It returns only a single value.
- It calculates the return value based only on its arguments.
- It doesn’t mutate any existing values.
Quick exercise 
Let’s quickly test your intuitions. Are these functions pure?
static int f1(String s) { return s.length() * 3;
} | static double f2(double x) {
return x * Math.random();
} |
Answers:
f1: yes, f2: no.
## Difficulty of staying pure ...
Now we know how we can write pure functions in our programming languages. Assuming they make our programming life better, why aren’t they more prevalent? The short answer is this: because we are not constrained to use them—languages we use don’t require us to.
The long answer, however, needs some background. Let’s go back to the function that calculates the price we’ll pay after a 5% discount.
```
static double f(double x) {
return x * 95.0 / 100.0;
}
```
We already know that it’s pure. However, Java doesn’t constrain us at all: **we could get away with a different, not-so-pure implementation** . Math, on the other hand, requires us to write only pure functions.
Math We are constrained a lot more when writing or changing mathematical functions. We can’t add “something more” to the function. If somebody uses our function f , they may safely assume that it returns a number when given a number. Math restricts the implementation from doing anything surprising. | Programming In most mainstream languages, we can change and add anything we want almost anywhere we want. In the function f , we could double f(double x) { spaceship.goToMars(); ①
return x * 95.0 / 100.0;
}① This function is no longer pure. Even worse! It is lying to us because it may not return a double if this Mars mission fails with an exception. And suddenly our promise to the user of f is broken. | |
The difficulty of staying pure comes from the fact that programming languages are usually a lot more powerful and elastic than math. However, _with great power comes great responsibility_ . We are responsible for creating software that solves real problems and is maintainable at the same time. Unfortunately, our powerful tools can backfire—and often, they do.
Let’s be more like math ...
We already know that the choice between writing pure functions and impure functions is ours to make. We know that we can transfer some of our knowledge of math to our programming endeavors. To do that, **we need to focus on three characteristics of a pure function and try to follow them wherever we go** .
## Pure functions and clean code
We discovered what rules we should follow to make functions pure. It turns out that all three rules have some specific effects on the way we work. They make our code cleaner. But wait! Their benefits don’t stop here. There are more!
Pure function
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
Single responsibility
When a function can return only a single value and can’t mutate any existing values, it can only do one thing and nothing more. In computer science, we say that it has a single responsibility.
No side effects
When a function’s only observable result is the value it returns, we say that the function doesn’t have any side effects.

Q What is a side effect?
A Anything a function does besides computing its return value based on its arguments is a side effect. So if your function does an HTTP call, it has side effects. If it changes a global variable or an instance field, it also has side effects. If it inserts something into a database, then yes, it has side effects! If it prints to the standard output, logs something using a logger, creates a thread, throws an exception, draws something on the screen, then ... you guessed it! Side effect, side effect, and side effect as well. \*
\* Don’t worry, it doesn’t mean you can’t do those things in a functional program! We will do many of them later in this book.
Referential transparency
When we can call a function many times—at different times of day and night but with exactly the same parameters—we get exactly the same answer. No matter what thread, what state the application is in, whether the database is up or down— `f(20), f(20), f(20)` will return `19, 19, 19` . This property is called _referential transparency_ .
If you have a referentially transparent function, you could substitute a function call, say `f(20)` , with its result, `19` , without changing the program’s behavior. If the function uses only its arguments to compute a value, and it doesn’t mutate any existing values, it automatically becomes referentially transparent.
## Coffee break: Pure or impure? 
Before we move on to refactoring some impure functions, let’s make sure you understand the three characteristics of a pure function.
**Your task is to** **judge if a given function has zero, one, two, or three of the pure function characteristics** . Zero means the function is impure; three means the function is pure. Any other value means the function is impure with some pure characteristics. For example:
```
static double f(double x) {
return x * 95.0 / 100.0;
}
```
Three characteristics are present (it’s a pure function).
_Now it’s your turn_ . Make sure you analyze each function thoroughly before answering. Use the pure function checklist to guide you. ↓
Pure function
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
```typescript
static int increment(int x) {
return x + 1;
}
static double randomPart(double x) {
return x * Math.random();
}
static int add(int a, int b) {
return a + b;
}
class ShoppingCart {
private List items = new ArrayList<>();
public int addItem(String item) {
items.add(item);
return items.size() + 5;
}
}
static char getFirstCharacter(String s) {
return s.charAt(0);
}
```
## Coffee break explained: Pure or impure? 
To solve this, we need to ask three questions about each function:
1. Does it always return a single value?
2. Does it compute its value based only on the data provided as arguments?
3. Does it stay away from mutating any existing values?
```
static int increment(int x) {
return x + 1;
}
```
Pure function
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
Yes, yes, and yes! It’s a pure function.

```
static double randomPart(double x) {
return x * Math.random();
}
```
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
Yes, no, and yes. This one returns only one value and doesn’t mutate any existing values, but it uses `Math.random()` to generate random data based on something more than the provided arguments (side effects).

```
static int add(int a, int b) {
return a + b;
}
```
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
Yes, yes, and yes again! Another pure function!

```
public int addItem(String item) {
items.add(item);
return items.size() + 5;
}
```
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
Yes, no, and no. This is an impure function. It returns just one value, but it doesn’t compute it based only on arguments (it uses `items` state, which may contain various values), and it doesn’t stay away from mutating existing values (again, it adds an item to the `items` state value).

```
static char getFirstCharacter(String s) {
return s.charAt(0);
} ①
```
① This one may be controversial because it’s an isolated example. Most often, exceptions are treated as another program flow. We’ll come back to this topic in chapter 6.
 Returns a single value
 Uses only its arguments
 Doesn't mutate existing values
No, yes, and yes. Another impure one. It doesn’t always return a value. It returns the first character of a given `String` or throws an exception (for the empty `String` ). It uses only data passed as an argument and doesn’t mutate any existing values.
## Using Scala to write pure functions
It’s time for more coding ! So far, we’ve seen that we can use Java to write simple pure functions without much hassle. This is also true in many other mainstream languages that support basic functional programming features and allow writing pure functions. However, some functional features that we are going to discuss later in the book have not gone mainstream (yet!), and we will use Scala to present them. \*
Thus, before we dive deeper, let’s stop for a moment and practice writing pure functions in Scala. Here’s the functional Java version:
```
class ShoppingCart {
public static int getDiscountPercentage(List items) {
if(items.contains("Book")) {
return 5;
} else {
return 0;
}
}
}
```
In Scala, we use the `object` keyword to create a single program-wide instance of an object. We use it as a container for pure functions. The Scala equivalent of the Java function above looks like this:
```
object ShoppingCart { ①
def getDiscountPercentage(items: List[String]): Int = { ①
if (items.contains("Book")) { ②
5 ②
} else { ②
0 ②
} ②
} ②
}
```
① `object` contains functions. `def` marks a function.
② There is no return key word because `if` in Scala and other FP languages is an expression. The last expression in the function is used as the return value.
Using this function is a little bit different than in Java, because **`Lists` in Scala are immutable,** which means that once they are created, they cannot be changed **.** Surprisingly, this helps a lot when programming functionally.
> | val justApple = List("Apple") ShoppingCart.getDiscountPercentage(justApple)
→ 0
val appleAndBook = List("Apple", "Book") ①
ShoppingCart.getDiscountPercentage(appleAndBook)
→ 5① We will focus on immutable values in the next chapter, so treat this as a sneak peek. |
\* We will show some code from different languages, not just Java, throughout the book. The main reason for that is to prove that techniques presented here are universal. Additionally, many of them are being introduced into traditionally imperative mainstream languages.
## Practicing pure functions in Scala 
**Your task is to** **rewrite the code below from Java to Scala** .
```typescript
class TipCalculator {
public static int getTipPercentage(List names) {
if(names.size() > 5) {
return 20;
} else if(names.size() > 0) {
return 10;
} else return 0;
}
}
List names = new ArrayList<>();
System.out.println(TipCalculator.getTipPercentage(names));
console output: 0
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(TipCalculator.getTipPercentage(names)); ①
console output: 10
names.add("Daniel");
names.add("Emily");
names.add("Frank");
System.out.println(TipCalculator.getTipPercentage(names));
console output: 20
```
① Note that in Java snippets we use `println` to show the value a function returns, while in Scala we just call the function and see the result as a REPL response. If you like this way better, you can try using `jshell` for Java expressions.
Notes:
\- `List` in Scala is created by using the constructor `List` `(...)` and passing all the items as comma-separated parameters.
\- You can create an empty list by calling a special function called `List.empty` `.`
\- `List` in Scala can’t be modified, so you need to create an instance for each case.
\- In Scala, a list of strings is written as `List[String].`
Answer
> | object TipCalculator { def getTipPercentage(names: List[String]): Int = {
if (names.size > 5) 20
else if (names.size > 0) 10
else 0
}
}
TipCalculator.getTipPercentage(List.empty) ①
→ 0
val smallGroup = List("Alice", "Bob", "Charlie")
TipCalculator.getTipPercentage(smallGroup)
→ 10
val largeGroup = List("Alice", "Bob", "Charlie", "Daniel", "Emily", "Frank")
TipCalculator.getTipPercentage(largeGroup)
→ 20① List.empty returns the empty list. Here, we pass an empty list as an argument. |
## Testing pure functions
One of the biggest benefits of working with pure functions is their testability. Easy testing is key to writing readable and maintainable production code. \*
Functional programmers often strive to have as many critical functionalities implemented as pure functions as possible. This way, we are able to test them using a very straightforward unit test approach.
Reminder: Using code snippets from this book
We have been using **`>`** at the beginning of code listings. Please remember it’s a sign that you should execute Scala REPL in your terminal ( **`sbt console`** ) and then follow the listing. Code listings that contain Scala REPL responses are marked as →.
> | def getDiscountPercentage(items: List[String]): Int = { if (items.contains("Book")) {
5
} else {
0
}
}
→ getDiscountPercentage
getDiscountPercentage(List.empty) == 1 ①
→ false ②
getDiscountPercentage(List.empty) == 0
→ true
getDiscountPercentage(List("Apple", "Book")) == 5
→ true ③① We don’t use any testing library here—just raw assertions (Boolean expressions). Since we are in the REPL, we can immediately get the result of an assertion. ② You get false in the REPL if your assertion is invalid. ③ We will use this style of assertions throughout the book. |
Note that pure function–based assertions are stunningly similar to real usage code. You just call a function! This helps a lot with writing better tests. A single line describes both the input and the expected output. Compare the three pure function tests above with a test you’d need to write for the imperative `ShoppingCart` we started with (in Java):
```
ShoppingCart cart = new ShoppingCart();
cart.addItem("Apple");
cart.addItem("Book");
assert(cart.getDiscountPercentage() == 5); ①
```
① This test has multiple lines of the test setup code, which doesn’t help readers understand what’s being tested as quickly as a single-line pure function call. This approach gets even more complicated when we test bigger classes.
As you can see, imperative code usually needs more test code because you need to set up all the state before making assertions.
\* Testing topics have their own chapter in this book (12), but we will briefly discuss some testing approaches and techniques before we get there to additionally highlight their importance.
## Coffee break: Testing pure functions 
When we use pure functions, we tend to make fewer mistakes. But the benefits don’t end there. Testing is far easier when using pure functions. The last coffee break of the chapter helps you write better unit tests.
**Your task is to write some unit tests for each of the pure functions below** . Try to write at least two assertions per function, with each one testing a different requirement. To write the best possible tests, do not look at implementations; just look at signatures and their requirements.
```
def increment(x: Int): Int = {
x + 1
}
def add(a: Int, b: Int): Int = {
a + b
}
def wordScore(word: String): Int = {
word.replaceAll("a", "").length
}
```
Treat the definition of the word score as a business requirement for a word game.
The `wordScore` function gets a string and returns the score of a given word in a word game. The score of the word is defined as the number of characters that are different than **`'a'.` .**
```
def getTipPercentage(names: List[String]): Int = {
if (names.size > 5) 20
else if (names.size > 0) 10
else 0
}
```
The `getTipPercentage` function gets a list of names and outputs a tip that should be added to the bill. For small groups (up to five people), the tip is 10%. For larger groups, 20% should be returned. If the list of names is empty, the answer should be `0` .
```
def getFirstCharacter(s: String): Char = {
if (s.length > 0) s.charAt(0)
else ' '
}
```
The function gets a `String` and returns its first character. In case an empty `String` is passed, the space character ( `' '` ) should be returned.
## Coffee break explained: Testing pure functions 
Here are some examples of valid tests. This list is by no means complete! Your tests are most certainly different, and that’s OK. The most important thing is to get acquainted with the difference between old-school stateful tests and functional tests of pure functions (plus some REPL exposure).
```python
def increment(x: Int): Int = {
x + 1
}
increment(6) == 7 ①
increment(0) == 1 ①
increment(-6) == -5 ①
increment(Integer.MAX_VALUE - 1) == Integer.MAX_VALUE ①
def add(a: Int, b: Int): Int = {
a + b
}
add(2, 5) == 7 ②
add(-2, 5) == 3 ②
def wordScore(word: String): Int = {
word.replaceAll("a", "").length
}
wordScore("Scala") == 3 ③
wordScore("function") == 8 ③
wordScore("") == 0 ③
def getTipPercentage(names: List[String]): Int = {
if (names.size > 5) 20
else if (names.size > 0) 10
else 0
}
getTipPercentage(List("Alice", "Bob")) == 10 ④
getTipPercentage(List("Alice", "Bob", "Charlie", ④
"Danny", "Emily", "Wojtek")) == 20 ④
getTipPercentage(List.empty) == 0 ④
def getFirstCharacter(s: String): Char = {
if (s.length > 0) s.charAt(0)
else ' '
}
getFirstCharacter("Ola") == 'O' ⑤
getFirstCharacter("") == ' ' ⑤
getFirstCharacter(" Ha! ") == ' ' ⑤
```
① Four tests should be enough to test different corner cases, such as incrementing positive value, negative value, `0` , and a value close to the maximum integer.
② Here are some cases with adding positive and negative values. We should also test maximum and minimum values as we did for `increment` .
③ A word with `a` ’s, a word without them, and an empty word.
④ A case for each requirement should be written: a small group, a large group, and the empty list.
⑤ A case for each requirement should be written: a normal word and an empty word. Additionally it’s good to confirm that words starting with a space will have the same answer as empty words (corner case).
I hope you enjoyed writing one-line, fast, and stable tests.
## Summary
That’s it! Let’s summarize everything we learned about pure functions.
Pure function
- It returns only a single value.
- It calculates the return value based only on its arguments.
- It doesn’t mutate any existing values.
CODE: `CH02_*`
Explore this chapter’s source code by looking at `ch02_*` files in the book’s repository.
Why do we need pure functions?
We started with a simple, imperative solution to a real-world problem. It turned out that the solution had some problems, which were connected to handling the state. We concluded that even simple, stateful, imperative computations may present some surprising challenges.
Passing copies of data
The first problem appeared when users of our class started using the `remove()` function on the `ArrayList` we returned. We learned that we can deal with such problems by passing and returning copies of data.
Recalculating instead of storing
There was one more problem left. Even after adding the `removeItem` API method (which turned out to be missing before), we didn’t handle state updates correctly, which left us with a corrupted state. We learned that we can remove some of the state and just recalculate the discount based on current cart contents every time the discount is needed.
Passing the state
We ended up with a class with five methods, four of which were just simple wrappers around `ArrayList` methods. We decided to remove this boilerplate and pass a `List` value directly to the `getDiscountPercentage` function instead. We ended up with a single small function that solves our problem.
Testing pure functions
Finally, we briefly talked about another big benefit of pure functions: how easy it is to test them. Testing is important because it doesn’t only ensure the correctness of a solution, but it also acts as its documentation. However, to achieve that, tests need to be concise and understandable. We will come back to this topic and discuss testing in depth in chapter 12.