In this chapter you will learn
- why mutability is dangerous
- how to fight mutability by working with copies
- what shared mutable state is
- how to fight mutability by working with immutable values
-
how to use immutable APIs of
StringandList
“ Bad programmers worry about the code. Good programmers worry about data structures and their relationships. ”
—Linus Torvalds
The fuel for the engine
In the last chapter we met the pure function, which is going to be our best friend throughout the rest of the book. We introduced and briefly discussed some caveats regarding values that may change—mutable states. This chapter focuses on problems with mutable states and explains why pure functions can’t use them in the majority of cases. We are going to learn about immutable values, which are used extensively in functional programming. The relation between a pure function and an immutable value is so strong that we can define functional programming using just two concepts.
Functional programming is programming using pure functions that manipulate immutable values . |
|
If pure functions make up the engine of functional programs, immutable values are its fuel, oil, and fumes.
Q How is it even possible to write fully working applications using only pure functions and values that can never change?
A The short answer is this: pure functions make copies of data and pass them along. We need specific constructs in the language to be able to easily program using copies. You can find out more by reading the longer answer in this and the following chapters.
Another case for immutability
We’ve already seen some problems a mutable state can cause when we met the pure function. Now it’s time to reiterate what we have learned and introduce even more potential problems.
The European trip
The context of our next example is a trip itinerary. Suppose we want to plan a trip around European cities: from Paris to Kraków. We draft the first plan:
List<String> planA = new ArrayList<>();
planA.add("Paris");
planA.add("Berlin");
planA.add("Kraków");
System.out.println("Plan A: " + planA);
console output: Plan A: [Paris, Berlin, Kraków]
But then we learn that one of our friends is a big fan of Mozart and insists on visiting Vienna before going to Kraków:
List<String> planB = replan(planA, "Vienna", "Kraków");
System.out.println("Plan B: " + planB);
console output: Plan B: [Paris, Berlin, Vienna, Kraków]
Our task is to write the replan function that will return an updated plan. It will need three parameters:
-
A plan that we want to change (e.g.,
[Paris, Berlin, Kraków]) -
A new city we want to add (e.g.,
Vienna) -
A city before which the new one should be added (e.g.,
Kraków)
Based on this specification and the usage example, we may conclude that the replan function should have the following signature:
Can you trust this function?
Let’s look at one of the possible implementations of the replan function. We will explain this implementation by going through our original example, adding Vienna before Kraków at the end:
List<String> planA = new ArrayList<>();
planA.add("Paris");
planA.add("Berlin");
planA.add("Kraków");
List<String> planB = replan(planA, "Vienna", "Kraków"); ①
① The code on the left is represented graphically using the diagram below. We use the gray area on the left to visualize variables and how they change over time (read top down).
As you can see, we first create planA, which is our original plan. Then, we call the replan function and request adding Vienna before Kraków.
Then, inside the It turns out that although |
|
System.out.println("Plan A: " + planA);
console output: Plan A: [Paris, Berlin, Vienna, Kraków] ①
① How did Vienna sneak into the original planA , if we had only added them in planB ?
What happened? Have a look at the top of the page where we created planA . It only had three cities then. How did Vienna sneak into the original plan if we had only added it in planB ? Unfortunately, the replan function doesn’t behave as promised. It does more than just return a new plan with a new city. It mutates more than just the returned list .
Mutability is dangerous
When we use a function that takes a List and returns a List , we assume that a new List is returned. But nothing stops this function from modifying the list it received as a parameter.
Now we know what happened! Unfortunately, replan lied to us. Even though the returned result is OK, the replan function additionally changed the list that we’d given it as an argument! plan inside the replan function pointed to the same list in the memory as planA outside the function. It promised to return a new value (the List return type suggests so), but instead it just mutated the list we’d given it as an argument! Changes to plan were applied to planA ...
Experienced developers may be quick to disregard this example as an obvious code smell, but again, please bear in mind that these problems are harder to detect in larger codebases.
Using mutable values is very dangerous . The replan is just a three-line function, so it’s possible to quickly look at the implementation and understand that it mutates the incoming argument, but there are far bigger functions that require us to pay a lot of attention to avoid introducing such a sneaky bug. There are many more things you need to focus on, and they are not related to the business problem at hand.
THIS IS BIG!
Avoiding mutability lies at the heart of functional programming.
Functions that lie ... again
To solve the problem with the replan function, we need to quickly recall what we discussed in chapter 2: pure functions . This information should give us additional insight into this particular problem we encountered and, hopefully, even more problems related to mutable values.
Is replan a pure function?
static List<String> replan(List<String> plan,
String newCity,
String beforeCity) {
int newCityIndex = plan.indexOf(beforeCity);
plan.add(newCityIndex, newCity);
return plan;
}
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.
|
|
Such functions are the worst because they mess with our intuitions. * To understand this better, let’s have a look at other mutating functions we can find in the List API and try to guess which ones are mutating something and may cause us similar headaches.
Again, these are three methods of the List class from the standard Java library. As you can see, all three of them use different approaches to mutations . This is very counterintuitive and leaves us error prone.
* Intuition is very important in programming. The more intuitive the API you work with, the more effective you will be and the fewer bugs you will make. That’s why we strive to use intuition to our advantage.
Fighting mutability by working with copies
To solve the problem we need to make sure that our replan function doesn’t mutate any existing values. We need to make sure that it is pure. Now that we know that users of our function expect us not to mutate values they provide as arguments, we can implement replan differently. We don’t need to change the API—just the internals:
static List<String> replan(List<String> plan,
String newCity,
String beforeCity) { ①
int newCityIndex = plan.indexOf(beforeCity);
List<String> replanned = new ArrayList<>(plan);
replanned.add(newCityIndex, newCity);
return replanned;
}
① Remember referential transparency? If we call the replan function multiple times with the same arguments, do we always get the same result? Before the refactoring, we didn’t. After this refactoring, we do! Our replan function is now referentially transparent!
Mutating values inside the pure function
Did you notice how we made a copy of the incoming argument, named it replanned , then mutated it using add ? How’s that not violating pure function rules?
To answer this question, please remember how the third rule of a pure function is constructed. ↓
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.
Pure functions don’t mutate any existing values. They can’t modify anything from the argument list or the global scope. However, they can mutate locally created values. In our case, |
We will show very soon that in functional languages we don’t have to mutate anything—even inside functions. Still, it’s good to know that many functional techniques can be used in traditionally imperative languages, like Java, without any additional functional libraries. |
System.out.println("Plan A: " + planA);
console output: Plan A: [Paris, Berlin, Kraków]
List<String> planB = replan(planA, "Vienna", "Kraków");
System.out.println("Plan B: " + planB);
console output: Plan B: [Paris, Berlin, Vienna, Kraków]
System.out.println("Plan A: " + planA);
console output: Plan A: [Paris, Berlin, Kraków]
Coffee break: Getting burned by mutability
It’s your turn to face the dangers of mutability. Here’s another problematic example that uses a different mutable method of |
|
Lap times
The most important things that are measured in motorsport are lap times. Cars or bikes are going around the circuit and try to record the best possible lap time. The quicker, the better! Here are two functions:
static double totalTime(List<Double> lapTimes) {
lapTimes.remove(0);
double sum = 0;
for (double x : lapTimes) {
sum += x;
}
return sum;
}
totalTime requirements
-
totalTimeshould return a total running time for all laps, excluding the first lap, which is an incomplete warm-up lap used to prepare the car and tires. -
Only lists with a minimum of two laps will be passed.
static double avgTime(List<Double> lapTimes) {
double time = totalTime(lapTimes);
int laps = lapTimes.size();
return time / laps;
}
avgTime requirements
-
avgTimeshould return average lap time, excluding the warm-up lap. -
Only lists with a minimum of two laps will be passed.
And here’s a sample usage of the functions above that generates a problem:
ArrayList<Double> lapTimes = new ArrayList<>();
lapTimes.add(31.0); // warm-up lap (not taken into calculations)
lapTimes.add(20.9); ①
lapTimes.add(21.1);
lapTimes.add(21.3);
System.out.printf("Total: %.1fs\n", totalTime(lapTimes)); ②
System.out.printf("Avg: %.1fs", avgTime(lapTimes));
① A list is created, and four lap times are added as doubles (in seconds).
② We print the results of the functions with 0.1 precision.
Think for a while about what could possibly go wrong there. Can you list as many potential problems as possible? Which part is the most suspicious? The code above, unfortunately, prints incorrect values:
Total: 63.3s
Avg: 21.2s
Your task is to figure out what the correct result should be and fix totalTime and/or avgTime accordingly .
Coffee break explained: Getting burned by mutability
First, let’s figure out what the correct result should be. We can try to calculate average and total time in our heads.
ArrayList lapTimes = new ArrayList<>();
total laps avg
lapTimes.add(31.0); // warm-up lap │ 0.0 0 -
lapTimes.add(20.9); │ 20.9 1 20.9
lapTimes.add(21.1); │ 42.0 2 21.0
lapTimes.add(21.3); │ 63.3 3 21.1
System.out.printf("Total: %.1fs\n", totalTime(lapTimes));
System.out.printf("Avg: %.1fs", avgTime(lapTimes));
If the functions had been written according to the specification, the code above would have printed
Total: 63.3s
Avg: 21.1s
But when we run it, we get the following:
Total: 63.3s
Avg: 21.2s ①
① Why is there 21.2 instead of 21.1 that we calculated manually?! What happened?
OK, so we got the proper result from totalTime ( 63.3 ). But why did we get a different average time ( 21.2 ) than the one we calculated manually ( 21.1 )? Was it a rounding error? Or just a bug in the function we missed?
Debugging mutations in totalTime
Let’s find out by debugging both functions, starting with totalTime .
The totalTime function gets a list of four lap times, removes the first one, then adds all the remaining doubles together, returning it back to the caller. It all seems reasonable, and indeed, we get the right result when we run it. So far so good.
Debugging mutations in avgTime
We can see that when we run avgTime in isolation, we get the correct result of 21.1 . So why did we get 21.2 when we run the code below? This is still a big mystery, but let’s not lose hope just yet.
System.out.printf("Total: %.1fs\n", totalTime(lapTimes));
console output: Total: 63.3s
System.out.printf("Avg: %.1fs", avgTime(lapTimes));
console output: Avg: 21.2s
Debugging mutations in both totalTime and avgTime
As you can see, the bug is not presenting itself when we use each function individually. It appears only when we use those functions in a bigger program. Mutation tricked us!
Making functions pure by mutating copies
We already learned how to deal with these kinds of problems. totalTime and avgTime are not pure functions because they mutate an existing value—in this case, lapTimes . To fix it, we need to work on a copy of the lapTimes inside both functions.
static double totalTime(List<Double> lapTimes) {
List<Double> withoutWarmUp = new ArrayList<>(lapTimes);
withoutWarmUp.remove(0); // remove warm-up lap
double sum = 0;
for (double x : withoutWarmUp) {
sum += x;
}
return sum;
}
static double avgTime(List<Double> lapTimes) {
double time = totalTime(lapTimes);
List<Double> withoutWarmUp = new ArrayList<>(lapTimes);
withoutWarmUp.remove(0); // remove warm-up lap
int laps = withoutWarmUp.size();
return time / laps;
}
Now, both functions are completely pure: they return a single value, which is computed based only on the arguments, and both of them don’t mutate any existing values. We can now trust those functions more because they behave more predictably. Again, this feature is called referential transparency . Our functions will return exactly the same value when we provide them exactly the same arguments—no matter what. ↓
If we can call a function multiple times with the same set of arguments and we always get the same result back, we say that this function is referentially transparent.
Can we do better?
Some of you probably wonder about the code duplication we introduced in the solution. Removing the warm-up lap functionality is duplicated in both functions. This is a slightly different problem, which violates a very popular rule: don’t repeat yourself (DRY ). We will address the problem and the rule later in this book because we need another tool to solve it functionally.
If you tried to solve this problem while doing the exercise and came up with a working solution that still doesn’t mutate any existing values, good for you! If not, however, don’t worry because you will learn how to do it soon enough. Right now, we need to focus only on avoiding mutability.
Introducing shared mutable state
The problem that hit us in our previous examples is just one of many that are related directly to using and manipulating a shared mutable state .
What is shared mutable state?
A state is an instance of a value that is stored in one place and can be accessed from the code. If this value can be modified, we have a mutable state . Furthermore, if this mutable state can be accessed from different parts of the code, it’s a shared mutable state .
Let’s go through our problematic examples and define which parts caused us headaches and could be categorized as a shared mutable state. *
* Note how we change our focus from functions that operate on data (i.e., add or remove ) to the data itself (i.e., plan and lapTimes ).
List<String> plan
-
This is a state because it can be accessed.
-
It’s mutable.
-
It’s shared (used and modified by
replanand inside the main program).
Here, the mutable shared state is the plan parameter! replan is not a pure function because of it.
List<Double> lapTimes
-
This is a state because it can be accessed.
-
It’s mutable .
-
It’s shared (by
avgTime,totalTimeand main program).
As you can see, both plan and lapTimes are shared mutable states.
Shared mutable state is the building block of imperative programming . * It may take different forms: a global variable, an instance field in a class, or any kind of read–write storage like a database table or a file. It can also be passed as an argument. Most importantly, as we have just witnessed, it can cause some serious problems.
* As you probably remember, imperative programming is all about following some step-by-step procedures. These procedures usually work on mutable states (e.g., sorting algorithms modify the arrays in place).
State’s impact on programming abilities
A programmer’s brain gets easily overloaded. While programming, we need to keep many things in mind. The more things we need to take care of, the higher the probability is of missing something or getting something wrong. This problem isn’t directly related to the mutable state, but programming in general. However, mutable state is a starting point to the rest of the discussion.
The more things we need to keep track of, the higher the cognitive load of a task is.
In the previous example, we had a replan function that took a plan as a parameter and returned a new plan. Even though we used planA as an input to replan and planB to store the result of calling the replan function, we were operating on the same mutable object the whole time!
Firstly, if we need to keep many things in mind to solve a programming problem—and usually we do—the problem gets a lot harder if these things can change anytime, such as between function calls or even between two lines of code (programming using threads).
Secondly, if these ever-changing things are additionally shared, there’s a problem of ownership and responsibility for them. We need to constantly ask ourselves: “Can I safely change this value?” “What other parts of the program use this value?” and “If I change this value, what entity should I notify about this change?”
Thirdly, if many entities can change a given state, we may have problems identifying all possible values of this state. It’s very tempting to assume that this state has values that can be generated only by the code at hand. But it’s a false assumption if this state is shared! Remember how we assumed that once a plan has been created, it cannot be changed because the replan function returns a new plan? ↓
Mutable shared states are that we need to pay attention to while programming. Each part can move independently and nondeterministically. This is what makes mutable shared states hard.
All these moving parts add to the complexity of our program. The bigger the codebase is, the harder all the above problems get! You have probably encountered a very common issue: changing a value in one place of the source code caused all sorts of hellish problems in another, seemingly very distant, place. This is the complexity of a shared mutable state in action.
Dealing with the moving parts
Finally, we can talk about techniques that directly deal with the moving parts , or shared mutable states. We’ll introduce three approaches: the approach used when we fixed the replan function, an object-oriented approach, and a functional approach.
Our approach
replan |
static List<String> replan(List<String> plan, ① String newCity, String beforeCity) { int newCityIndex = plan.indexOf(beforeCity); List<String> replanned = new ArrayList<>(plan); ② replanned.add(newCityIndex, newCity); return replanned; ③ } ① This is a pure function. It returns a single value, which is calculated based only on the arguments. It also doesn’t mutate any existing values. ② We need to make sure it doesn’t mutate any existing values by creating a totally new list and copying elements from the incoming list. ③ This function can be trusted. You will always get the same result if you provide the same arguments. |
Itinerary |
private List<String> plan = new ArrayList<>(); ① public void replan(String newCity, String beforeCity) { int newCityIndex = plan.indexOf(beforeCity); plan.add(newCityIndex, newCity); ② } public void add(String city) { ③ plan.add(city); } public List<String> getPlan() { return Collections.unmodifiableList(plan); ③ } ① In object-oriented programming, data and methods that change this data are coupled together. Data is private; it can be mutated only by methods. ② This method returns ③ If we allow mutations, we need to explicitly expose them as separate methods. ④ We need to be very careful not to leak the internal data to the users of the class. We need to return a copy or a view to make sure nobody else mutates our state (i.e., it doesn’t become shared). The bigger the class is, the more taxing and error-prone this becomes. |
replan |
def replan(plan: List[String], ① newCity: String,
beforeCity: String): List[String] = {
val beforeCityIndex = plan.indexOf(beforeCity)
val citiesBefore = plan.slice(0, beforeCityIndex)
val citiesAfter = plan.slice(beforeCityIndex, plan.size)
citiesBefore.appended(newCity).appendedAll(citiesAfter)
}① |
> | val appleBook = List("Apple", "Book") → List("Apple", "Book")
val appleBookMango = appleBook.appended("Mango") ①
→ List("Mango", "Apple", "Book") ②
appleBook.size
→ 2
appleBookMango.size
→ 3① Make sure you use the Scala version we installed in chapter 1. If you have problems finding the ② This function adds an element at the end of this |
replan |
static List<String> replan(List<String> plan, ① String newCity, String beforeCity) { int newCityIndex = plan.indexOf(beforeCity); List<String> replanned = new ArrayList<>(plan); ② replanned.add(newCityIndex, newCity); ③ return replanned; } ① This is a pure function. It returns a single value, which is calculated based only on the arguments. It also doesn’t mutate any existing values. ② We need to make sure it doesn’t mutate any existing values by creating a totally new list and copying elements from the incoming list. ③ This function can be trusted. You will always get the same result if you provide the same arguments. |
Write the function called firstTwo(List("a", "b", "c")) == List("a", "b")
| 1 |
Write the function called lastTwo(List("a", "b", "c")) == List("b", "c")
| 2 |
Write the function called movedFirstTwoToTheEnd(List("a", "b", "c")) == List("c", "a", "b")
| 3 |
Write the function called insertedBeforeLast(List("a", "b"), "c") == List("a", "c", "b") | 4 |
> | def firstTwo(list: List[String]): List[String] = list.slice(0, 2)
def lastTwo(list: List[String]): List[String] =
list.slice(list.size - 2, list.size)
def movedFirstTwoToTheEnd(list: List[String]): List[String] = {
val firstTwo = list.slice(0, 2)
val withoutFirstTwo = list.slice(2, list.size)
withoutFirstTwo.appendedAll(firstTwo)
}
def insertedBeforeLast(list: List[String], element: String): List[String] = {
val last = list.slice(list.size - 1, list.size)
val withoutLast = list.slice(0, list.size - 1)
withoutLast.appended(element).appendedAll(last) ①
}① We use |



