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 String and List

“ 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 replan function, we first figure out before which index the new city (Vienna) should be added (Kraków has index 2 ). We add Vienna at this index, moving all the other cities one index forward and expanding the list. Finally, we return and save the result as planB . We get the desired result, but we can’t celebrate just yet.

It turns out that although planB seems to be correct, when we try to print our original planA , it’s different than what we created.

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.

replan returns only one value and calculates it based on the provided arguments. But, as it turned out, it mutates existing values (in this case it mutates a list provided as the first argument: plan ). So the answer is this: no, replan is not a pure function . Even worse! We needed to look at the implementation to be able to figure it out! At first, we just looked at its signature and assumed that it was a pure function. Then, we used it accordingly. That’s how bugs are introduced.

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, replan creates a mutable List , modifies this list, then returns it. This is what we did in the replan function. Note that the Java programming language supports only mutable collections. However, we can still use the power of pure functions by mutating newly created copies inside functions. After this small change, the replan function behaves as expected, and we don’t have any surprises waiting for us.

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 List .

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

  • totalTime should 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

  • avgTime should 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 replan and 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 , totalTime and 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.

Object-oriented approach In object-oriented programming (OOP) we’d probably use _encapsulation_ to guard the changing data. Encapsulation Encapsulation is a technique that isolates a mutable state, usually inside an object. This object guards the state by making it `private` and making sure that all mutations are done only through this object’s interface. Then, the code responsible for manipulating the state is kept in one place. All the moving parts are hidden.

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 void because it mutates data in place. We lose the previous version of the plan. Additionally, it can’t be trusted because the result of calling it with the same arguments may be different (depending on the state).

③ 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.

## Dealing with the moving parts using FP The time has come to introduce the second very important piece of our functional toolkit. We danced a long time around this topic, meeting all the mutable and impure villains along the way. We know that OOP uses encapsulation to fight them. What does FP have to say? Functional approach (but used in OO code as well, and getting popular) The functional approach takes a different perspective: it tries to minimize the amount of moving parts—and ideally get rid of them completely. Functional codebases don’t use shared mutable states, they use _immutable states_ , or simply immutable values that act as states. THIS IS BIG! We don’t use mutable states in FP—we use immutable ones instead. Immutable values A technique that guarantees that once a value is created, it can never be changed. If a programmer needs to change even the slightest portion of a value (e.g., add a string to a list), a new value needs to be created and the old one left intact. Using immutable values instead of mutable ones eliminates a whole bunch of issues we have been discussing in this chapter. It also deals with the problem we encountered in our `replan` function. So where’s the catch? Well, it’s a brand-new world; we need to learn how to use immutable values in a more practical setting. We will need to use Scala, where immutable collections, including lists, are built in. Sneak peek at the functional approach in Scala Over the following pages, we will learn the fully functional approach that embraces immutable values. We will implement the `replan` function in Scala. As a sneak peek, have a look at the final solution below. Don’t worry if you don’t get it yet—we will explain all the details along the way.

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)
}

① List in Scala is immutable. Every operation returns a new List , always. Here, we use the combination of List.slice , List.appended , and List.appendedAll to add a given new city before the specified city. This works as intended and doesn’t mutate any values.

## Immutable values in Scala If we want to design functions that use immutability, we need to use tools that are well suited for this. As we saw in our last example, Java’s `List` and `ArrayList` are mutable, and we need to do some tricks to use the powers of a pure function. These tricks work fine, but there is still room for improvement. It’s about time we get back to coding in Scala. And the reason is that **Scala has native support for immutability.** \* For example, the `List` type in Scala is immutable by default; we can’t mutate it in place. \* The same can be said about any other functional language. No matter what functional language you choose, you can expect that immutability is built in. Reminder: Using code snippets from this book It’s been a while since we last touched Scala and the REPL, so I owe you a quick reminder of the convention we use in the book. Whenever you see a code snippet with **\>** on the left, it means that we expect you to follow the code in your Scala REPL session (type `“sbt console”` in the terminal). Press Enter after each line, and your REPL should give you an answer similar to the one you see in the book after the **→** sign. Make sure you use the correct version of Scala before proceeding. If you have any issues, please refer to the guide in chapter 1. Checking out `List` in Scala REPL Let’s prove that these are not just empty promises, and Scala really has built-in support for immutability. Fire up the Scala REPL, and write

>

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 appended function, you may be working with an old Scala version.

② This function adds an element at the end of this List . Note that this is not the idiomatic way of adding items to a List in Scala, due to its lacking performance (it needs to copy the whole original list), but it works fine for small lists.

As you can see, we have `appended` (i.e., added at the end) a _Mango_ to a `List` that already included an _Apple_ and a _Book._ We named this list, rather uninspiringly, `appleBookMango` . Then, we checked sizes of both `List` s, and it turned out that our original `appleBook` list didn’t change after appending a new element! The size was still exactly `2` . That means we got a new `List` back! Truth is, **Scala’s** `List` **cannot be mutated** . Each operation returns a new `List` , no matter what. ## Building our intuition about immutability It’s time to move into the immutable world. Let’s do it gently, though. We will be using Scala’s `List` API, which is immutable. But before we start using it to solve the problem with the `replan` function, let’s practice using the immutable API we all already know well: `String` ! Let’s compare Scala’s `List` API with Java’s `String` API. ![](/images/book/grokking-functional-programming/6079f221-be6d-4949-b68a-0ddc16851541.png) `String` is immutable. If you understand how `String` works, you will be able to grasp immutable collections with ease. If not, don’t worry: we will play with `String` a bit before moving on. ## Coffee break: The immutable `String` API ![](/images/book/grokking-functional-programming/771c0663-f0ea-46dc-8fb7-07e7dcabd466.png) Let’s play with Java’s `String` API, but in ... Scala! Scala uses the same `String` class as Java, so treat this as a gentle introduction to using immutable APIs and a way of practicing Scala. **Your task is to implement the** **`abbreviate` function** that takes a `String` consisting of a full name and returns an abbreviated version. ![](/images/book/grokking-functional-programming/8bf08e82-0cd2-40bd-a332-f5d28fbd8940.png) The `abbreviate` function should get one `String` as an argument and return a new one with the result. So if we call it with `"Alonzo Church"` , \* we should get `"A. Church"` back. \* Alonzo Church was a mathematician who developed the lambda calculus—the foundation of FP. ![](/images/book/grokking-functional-programming/8d40d2e8-0ac4-44a5-ae09-05643d0478cb.png) Remember that the `abbreviate` function should be a pure function and manipulate only immutable values. No mutations! Use the power of creating new values based on some existing ones. 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. Here are a few additional hints: - Scala’s `String` is exactly the same as Java’s, so you can use your existing knowledge or go through `String` ’s documentation to implement `abbreviate` . - Java’s `String` has an immutable API, so if you just restrain yourself to using `String` ’s methods, you can be sure that your implementation is pure and you don’t mutate anything. - Please use Scala in this exercise. As a quick reminder, functions are defined using the `def` keyword : ``` def function(stringParameter: String): String = { ... } ``` ## Coffee break explained: The immutable `String` API ![](/images/book/grokking-functional-programming/771c0663-f0ea-46dc-8fb7-07e7dcabd466.png) First, let’s define manually what we need to achieve. ![](/images/book/grokking-functional-programming/0b1f3f9d-7edc-45cf-a3dd-8006d31ad5ea.png) Note how we focused on defining relations between the incoming values and values we need to create. Using _is_ in requirements is important and very helpful because we can easily encode each of them as immutable values. Look how we focus on what needs to be done and not how it’s done. It’s declarative programming. ![](/images/book/grokking-functional-programming/f2f861e5-048b-4a81-b4fb-31c4d0758b2e.png) So the final implementation could look like this: ``` def abbreviate(name: String): String = { val initial = name.substring(0, 1) val separator = name.indexOf(' ') val lastName = name.substring(separator + 1) initial + ". " + lastName } ① ② ``` ① Remember that we don’t use the `return` keyword in Scala. The result of the last expression is automatically returned. ② Note that we ignored error handling. We’ll take care of it in chapter 6. Of course, this is just one of the possible implementations. The most important thing is to make sure that your code doesn’t mutate values. ## Hold on ... Isn’t this bad? Functional programming is all about pure functions that manipulate immutable values. This means that every expression creates a new object, either from scratch or by copying parts of another object. **No values can be mutated.** Here are some questions you may have about this approach: THIS IS BIG! In FP, we just pass immutable values around! Q Isn’t copying bad in terms of performance? A Yes, it’s worse than just modifying things in place. However, we can argue that it’s usually not relevant in the majority of applications. This means that in many cases readability and maintainability of the codebase far exceeds a potential performance drop.                 ↑ Another way to look at both problems is that mutability can be used as an optimization technique in some scenarios. You can still use mutability and hide it inside a pure function, as we did earlier. Most importantly, you do this only in exceptional cases after a deliberate performance analysis of your program.                 ↓ Q So, if I’m using functional programming, my applications will be slow? A Not necessarily. The best approach to performance analysis is, firstly, making sure that you are optimizing the right thing. You need to find the bottleneck and only then try to optimize it. If you are sure that an immutable operation is the main culprit, you still have several options. For example, if your problem is that you are frequently adding something to a very big list, then instead of `appended` you can use the `prepended` , function that adds an element at the beginning in constant time without copying or changing the old one. We’ll discuss recursive values in chapter 9.                                                    ![](/images/book/grokking-functional-programming/51463571-8de6-4525-bf3d-b8cc604a7cdc.png) Q Why can’t I just use Java’s `Collections.unmodifiableList` ? A `unmodifiableList` takes a `List` as a parameter and returns a `List` , which is just a “view" of the original `List` . This view acts as a `List` , but it cannot be modified. The `add` method is still there and can be called... but it will result in a runtime exception, which violates our trust. Additionally, even if we return an “unmodifiable" `List` to our user, we can still mutate the original one! Hence, the user doesn’t have any guarantees about the returned value, and all the shared mutable state problems we have discussed can still appear. We’ll discuss exception handling in chapter 6. ## Purely functional approach to shared mutable state We have almost all the tools we need to solve the `replan` problem (and many more similar ones) using a purely functional approach in Scala. Here’s the last version we implemented.

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.

Now we are able to deal with the highlighted problem because Scala, like any other FP language out there, has built-in support for immutable collections. If we use Scala’s `List` , we don’t have to worry about any potential mutations. It’s just not possible to mutate anything! Focusing on relations between values Before implementing anything, let’s stop for a moment and see how we can analyze such problems and arrive at purely functional solutions to them in the future. The trick is to **always start with listing all known relations between the incoming values and the value we want to produce** . THIS IS BIG! Immutability makes us focus on relations between values. ![](/images/book/grokking-functional-programming/48323138-967d-4570-8eb1-efe8c8f922f6.png) Transforming relations into expressions When we have all the relations between the incoming values and the desired result, we can try to encode them as Scala expressions. ![](/images/book/grokking-functional-programming/31b7df14-9b0b-4ea0-aab4-6e706376d9ba.png) ![](/images/book/grokking-functional-programming/94897b94-a506-4140-a0ea-1055075c4651.png) Putting expressions into the function body The hard part is already done! Now, we just need to copy these expressions into compiling Scala code and write the function’s signature: ``` 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) } ``` And _voilà!_ That’s it—we have the working implementation, which doesn’t have any problems related to shared mutable state. We used the immutable Scala `List` , and we can be sure that this function is pure; therefore, we can trust that it will always behave in the same way! ## Practicing immutable slicing and appending ![](/images/book/grokking-functional-programming/e8e532cd-66e6-4614-a81d-60064e7e3377.png) It’s time to **write** **some functions using the immutable** **`List` in Scala** :

Write the function called firstTwo , which gets a list and returns a new list that contains only the first two elements of the incoming list. This assertion should be true:

firstTwo(List("a", "b", "c")) == List("a", "b")

1

Write the function called lastTwo , which gets a list and returns a new list that contains only the last two elements of the incoming list. The assertion below should be true:

lastTwo(List("a", "b", "c")) == List("b", "c")

2

Write the function called movedFirstTwoToTheEnd , which gets a list and returns a new list with the first two elements of the incoming list moved to the end. The following assertion should be true:

movedFirstTwoToTheEnd(List("a", "b", "c")) == List("c", "a", "b")

3

Write the function called insertedBeforeLast , which gets a list and a new element. It returns a new list that has the element inserted before the last element of the incoming list . The assertion below should be satisfied:

insertedBeforeLast(List("a", "b"), "c") == List("a", "c", "b")

4

Answers

>

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 appendedAll because last is a List that contains one element.

Note we can omit braces in Scala, and the compiler will not complain. ## Summary Let’s summarize all the things we’ve learned about immutable values. CODE: `CH03_*` Explore this chapter’s source code by looking at `ch03_*` files in the book’s repository. Mutability is dangerous We started with a simple, imperative solution to a real-world problem. It turned out that the solution had some problems that were connected to operations on Java’s `List` , which were changing the list given as the argument. We discovered that we need to pay special attention when using mutable collections. Just looking at the signature is not enough. We need to look very closely at the implementation to avoid getting burned by mutability. Fighting mutability by using copies We solved the problem by copying the incoming list and working only on the copied version inside the function. This way we made sure that the users of the function wouldn’t be surprised. What is shared mutable state? Then, we tried to understand why mutability is such a big problem. We introduced shared mutable state, which is a variable that is shared between different entities in the codebase and can be mutated by them. Fighting mutability by using immutable values Finally, we introduced a more powerful technique to deal with shared mutable states: immutable values. If our functions take only immutable values and return immutable values, we can be sure nothing is unexpectedly mutated. Using immutable APIs of `String` and `List` At the end, we learned that Java’s `String` is already using this approach because many of its methods return a new value of `String` . We learned that Scala has built-in support for immutable collections, and we played a bit with `List` ’s `slice` , `append` , and `appendAll` functions. We will spend the rest of the book learning about all kinds of immutable values. Functional programming is programming using _pure functions_ that manipulate _immutable values_ .