In this chapter you will learn

  • how to handle all errors without null s and exceptions
  • how to make sure all corner cases are handled
  • how to indicate all the possible errors in the function signature
  • how to compose bigger functionalities from smaller functions in the presence of different possible errors
  • how to return user-friendly and descriptive errors

“ There are two ways to write error-free programs; only the third one works. ”

—Alan Perlis, “Epigrams on Programming”

Handling lots of different errors, gracefully

We can’t write code that never fails. That’s why we need to embrace all possible errors and make sure our code can handle them and recover from them gracefully. In this chapter we will discover how helpful it is to think about errors in terms of immutable values returned from pure functions. As always, we will learn based on a real-world example:

TV show–parsing engine

In this chapter we’ll be dealing with popular TV shows. We’ll start with simple requirements and then add more of them to make a full-blown TV show–parsing engine. There will be lots of corner cases to handle. We’ll use them to learn how to use FP techniques to make sure all of them are covered gracefully without polluting the codebase.

We will work with raw values (i.e., values that are Strings) . This will simulate real applications that get their data from the outside: a web service or a database. It may also simulate getting real user input. You will implement a few requirements yourself, but before you do, let’s look at the trickiest one to understand how much you will learn.

What you will learn in this chapter

Here’s a snippet of the example we will do later in this chapter. You will get a list of Strings that represent TV shows. Your function, called parseShows , will need to parse all these Strings and return the shows inside a nicely defined three-field TvShow value:

val rawShows = List("Breaking Bad (2008-2013)", ①
                    "The Wire (2002-2008)",     ①
                    "Mad Men (2007-2015)")      ①
parseShows(rawShows)

List(TvShow("Breaking Bad", 2008, 2013),
       TvShow("The Wire", 2002, 2008),
       TvShow("Mad Men", 2007, 2015))

① We have a list of TV shows that are represented by raw strings that came from the outside world (a service or a database).

Is it even possible to handle them all?

Can we really handle all of these errors and still have great signatures, small implementations, immutable values, and pure functions? This chapter will resolve these doubts. But before we implement the real version of parseShows , which is prepared for all kinds of errors, we will need to recap some things about passing functions as parameters and returning functions (higher-order functions). Then, we will start learning about handling errors by looking at small functions and small errors. Next, we will build more functions by composing other small functions. This approach will work even when all of these functions fail.

Note how we are building on top of knowledge we gained in previous chapters. It’s all about reusing the same blocks in more and more advanced scenarios.

We will use these graphics during the course of the chapter to let you know how far along we are.

Apart from learning about functional error handling, you will get a chance to use almost all the things you’ve learned so far. Let’s go!

Sort the list of TV shows by their running time

We will start with a warm-up exercise that will help us recap some things about higher-order functions we learned in chapter 4 and get acquainted with our new problem and its domain.

Requirement: Given a list of TV shows, sort it by running time

  • We get a list of TV shows.

  • Each TV show has a name, the year it started airing, and the year it concluded.

  • We need to return a new list of TV shows, sorted by their running time, descending.

Quick exercise: The signature

Before we move on, we need you to design two things for us: a model of a TV show that we’ll use and a signature of a pure function that will fulfill the requirement. This is how we usually start implementing requirements, both in this book and in real-world applications. That’s why it’s important not to skip this part. Please stop reading for a while and try to answer these questions:

Answers in discussion.

  1. What would a product type called TvShow look like?

  2. What would a signature of a function called sortShows look like?

Q Didn’t we implement a similar function before?

A Yes, we did. It’s repeated here on purpose. If it’s easy for you, then great! The twist to this problem comes very soon, so please stay tuned.

The immutable model and the signature

Figuring out the model and a function signature is usually very hard, * but if it’s done right, we are rewarded with a straightforward implementation.

* Note how this becomes a recurring theme in this book. We start implementing a requirement with two steps: a model (a product type) and a signature of a pure function.
That’s how FP works: we program with pure functions, which manipulate immutable values.

We’ll use the following product type to model a TV show. TvShow should have a name, a year it started airing, and a year it ended. We just need to translate this sentence from English to Scala:

case class TvShow(title: String, start: Int, end: Int)

The signature of sortShows can also be translated directly from English to Scala:

def sortShows(shows: List[TvShow]): List[TvShow]

Implementing the sorting requirement

We have the signature , so a big chunk of the requirement is already done. Now we need to provide an implementation that satisfies the signature.

Requirement: Given a list of TV shows, sort it by running time

  • We get a list of TV shows.

  • Each TV show has a name, the year it started airing, and the year it concluded.

  • We need to return a new list of TV shows, sorted by their running time, descending.

To implement sortShows , we need to recall our old friends—functions that are defined for Lists — sortBy and reverse :

def sortShows(shows: List[TvShow]): List[TvShow] = {
  shows
    .sortBy(tvShow => tvShow.end - tvShow.start)    ①
    .reverse                                        ②
}

① sortBy returns a new List that contains the same elements as the input List but sorted using a function provided as a parameter. Here, this anonymous function returns an Int : number of years a given show was running.

② sortBy sorts in a natural order (from the smallest Int to the largest one), so to have a descending order, we need to reverse the List .

Using sortShows

Let’s try to use the new sortShows function and make sure it works fine.

>

val shows = List(TvShow("Breaking Bad", 2008, 2013),                   TvShow("The Wire", 2002, 2008),
                 TvShow("Mad Men", 2007, 2015))
 
sortShows(shows)
→ List(TvShow("Mad Men", 2007, 2015), ①
        TvShow("The Wire", 2002, 2008),
        TvShow("Breaking Bad", 2008, 2013))

① Mad Men ran for eight years, so it’s at the top of the list.

The twist OK, enough with warm-up exercises! Where is the catch? It turns out **we won’t get the list of TV shows as a `List[TvShow]`** \* . We will get it as a `List[String]` ! It’s a pretty common scenario—we get data from the outside world: a database, a web service, or user input. So we usually need to deal with a raw `String` . In our case it’s a `List` of `Strings` , each representing a single TV show and its details. Welcome to the real world! \* It is the first time we take into consideration that no application works in isolation. Each application we create needs to communicate with the outside world. This communication usually happens using low-level primitives, like `String` s. ## Dealing with data coming from the outside world So far we’ve been working with an ideal world scenario. We’ve always had object instances that contained only validly formatted data. We were operating on `Books` , `Events` , `Points` , `ProgrammingLanguages` —and now `TvShows` . It’s been great but a little bit off. The real world is scarier than that. We need to operate on lower levels; we are getting raw inputs from the user; we are getting raw data from other services and even from our own database. There is always something that could go awry. We are now going to start learning about these scary real-world scenarios based on parsing incoming data. We don’t really get a `List[TvShow]` , we get a `List[String]` , and each of the `Strings` aims to represent a TV show, but it’s our job to make sure each of these `String` s really is a TV show. This operation is called **parsing** . Parsing Parsing is an operation that transforms raw data, like `String` , into a domain model, usually represented by a product type (immutable value). We will use parsing to show how to deal with raw data coming from the outside world. This means that we will need to deal with all sorts of problematic scenarios. Note that **this chapter is not about parsing** . We just use parsing as an example of a potentially failing operation. All the techniques we use for parsing `String` s can, and will, be used for other failing operations later in the book. You most definitely know what parsing is. We mention it here explicitly because it occupies a special place in functional programming. For example, we have parser combinators, which are used to create more complicated parsers from basic ones using higher-order functions. It’s the essence of FP. Here’s the problem we now have to deal with:

>

val rawShows: List[String] = List(    "Breaking Bad (2008-2013)",                      ①
  "The Wire (2002-2008)",                          ①
  "Mad Men (2007-2015)")                           ①
  
sortShows(rawShows)
→ compilation error: sortShows takes List[TvShow] ②

① We now have a list of String s, each potentially representing a TV show.

② sortShows needs List[TvShow] , so if we provide a List[String] , it will protest loudly.

The natural question arises: do we now need to reimplement `sortShows` ? It needs a new signature! It needs to take a `List[String]` and return a sorted `List[TvShow]` , right? Well, **the answer is no** . ## Functional design: Building from small blocks The whole point of the functional design is to build bigger functionalities from small pieces: pure functions from smaller pure functions. Let’s transfer this principle to our current example. We got the requirement about sorting, and we just implemented it. ``` def sortShows(shows: List[TvShow]): List[TvShow] = { shows .sortBy(tvShow => tvShow.end - tvShow.start) .reverse } ``` It’s a pure function that gets a `List[TvShow]` and returns a new list, sorted according to the requirements. The fact that the input type changes doesn’t matter for this requirement; **it’s a completely different requirement that should be implemented as a separate function!** This way we can focus on one thing at a time. We focused on sorting, and now it’s time to focus on parsing the raw input. The new requirement needs a new function. Let’s think for a bit. We have a `List[String]` , and we have function that needs a `List[TvShow]` as an input. That means that we need a new function that transforms a `List[String]` into a `List[TvShow]` . We’ll then be able to compose both of those functions using a technique for sequential programs. ![](/images/book/grokking-functional-programming/ab3a2ad4-ba51-4ab1-95a8-980d75a11dce.png) This way we don’t have to change `sortShows` at all! It’s small and does its job. That’s the beauty of functional design. We do everything using small functions with single responsibilities. The composition is also a small function with one responsibility (merging two other ones). ``` def sortRawShows(rawShows: List[String]): List[TvShow] = { val tvShows = parseShows(rawShows) sortShows(tvShows) } ``` We will now move on to more advanced cases and leave sorting behind. Remember, however, that it still is there and can be used without modification. The following pages will focus on implementing the `parseShows` function with error handling. ## Parsing `Strings` into immutable objects Let’s leave sorting behind for now. It’s done, and we know it’s working as intended. We know that it’s been implemented using a pure function and immutable values, so it will be very easy to use it later. Before we can use it, however, we need to make sure that we have a `List[TvShow]` that `sortShows` needs as an input. However, all we have now is a `List[String]` . Therefore, we need a function that takes a `List[String]` and returns a `List[TvShow]` . ``` def parseShows(rawShows: List[String]): List[TvShow] ``` Before we try to implement it, let’s try to list the requirements of parsing. You have probably guessed them already. New requirement: Format of a raw TV show           ![](/images/book/grokking-functional-programming/582e80fa-3e55-4ef7-8ef2-80ca19016d80.png) Our application gets a `List` of raw TV shows. Each raw TV show is just a `String` that should have the following format: ``` TITLE (YEAR_START-YEAR_END) ``` For example: In `"The Wire (2002-2008)"` , `TITLE` is `"The Wire"` , `YEAR_START` is `2002` , and `YEAR_END` is `2008` . The `String "The Wire (2002-2008)"` should, therefore, be transformed into an immutable value of `TvShow("The Wire", 2002, 2008)` . The format is `TITLE (YEAR_START-YEAR_END)` . So our algorithm should do the following steps: 1. Find the occurrence of `'('` and treat everything before it as a title (and trim all whitespaces). 2. Find the occurrence of `'-'` and treat everything between `'('` and `'-'` as a starting year (it should be parsable to `Int` ). 3. Find the occurrence of `')'` and treat everything between `'-'` and `')'` as an end year (it should be parsable to `Int` as well). As you can see, there is a lot going on here. On top of that, we have a `List[String]` , so we need to apply this algorithm to each `String` in this list. A lot can go wrong here, so our first reflex is to **split it up more** . ## Parsing a `List` is just parsing one element We have a `List[String]` and an idea for an algorithm that transforms one `String` into a `TvShow` .

Quick exercise

Before moving on, let’s think for a bit. Do you remember what function defined on List we can use here to make our job easier?

Answer in discussion.

Before answering the question, let’s approach it from the software architecture and design perspective. The first rule of functional design is to split a given requirement into small functions before implementing anything. We can do it by working with small, one-line implementations and signatures only, thus making it more about the design and less about the nitty-gritty details. In our case we want to parse an incoming `List[String]` into a `List[TvShow]` . Parsing a `List` by parsing each element separately A functional way of solving it is to extract the functionality of parsing just one `String` into a `TvShow` and then use it to parse the whole `List` . Sound familiar? It’s our old friend, `map` ! ``` def parseShows(rawShows: List[String]): List[TvShow] = { rawShows.map(parseShow) } ``` ![](/images/book/grokking-functional-programming/823b32d0-7de1-4462-8eb1-abe4cb0de66d.png) As you can see, we are mapping each `String` element using a function called `parseShow` , which should return a `TvShow` . This function has not been written yet, but we already know what signature we need! \* Now what’s left to implement is a smaller function that takes care of parsing a single TV show: ``` def parseShow(rawShow: String): TvShow ``` \* Note the subtle difference between `parseShows` , which is implemented using a `map` , and a `parseShow` , which we haven’t written yet, though we already know how we’ll use it. Now we can focus on implementing the smaller function ( `parseShow` ) because the bigger one is already done ( `parseShows` )! After we implement the small function that parses one `String` , we will automatically gain the ability to parse the `List[String]` as well! This is the functional design at work! We have thought the functionality through, broken it down into smaller pieces, and reused some superpowers we learned about earlier. Let’s implement the `parseShow` function! ## Parsing a `String` into a `TvShow` Let’s try to implement the function that parses one `String` into a `TvShow` . Based on the requirements, given a well-formatted `String TITLE (YEAR_START-YEAR_END)` , `parseShow` should first look for separator characters (brackets, dash) and then extract the information like this: ![](/images/book/grokking-functional-programming/098475bd-818b-4dee-b5b6-e74c2af4f4e1.png) Let’s try to use it and find out if it works correctly.

>

parseShow("Breaking Bad (2008-2013)")  → TvShow("Breaking Bad", 2008, 2013)
It does! Additionally, as promised, implementing the `parseShow` function should automatically give us the power to use `parseShows` , which was implemented using a `map` . ``` def parseShows(rawShows: List[String]): List[TvShow] = { rawShows.map(parseShow) } ``` When we try to use it, everything works just fine! We get a list back! ``` val rawShows: List[String] = List( ① "Breaking Bad (2008-2013)", "The Wire (2002-2008)", "Mad Men (2007-2015)") ``` ① We have an input list of raw shows: three `String` s that represent potential TV shows in a format we require.

>

parseShow(rawShows)  ①  → List(TvShow("Breaking Bad", 2008, 2013),
        TvShow("The Wire", 2002, 2008),
        TvShow("Mad Men", 2007, 2015))

① When we use the rawShows list as an input to our parseShows function, it map s each String using the parseShow (singular) function and returns a new list, with proper TvShow immutable values.

## What about potential errors? We now have our new `parseShow` and `parseShows` functions, and they produce correct results for our sample list of raw TV shows. So are we done already? The answer, unfortunately, is no; we are not done. As we mentioned earlier, the raw `Strings` are something coming from the outside world, a database, or user input. That means that we may, and most certainly will, not get all these `Strings` formatted as `TITLE (YEAR_START-YEAR_END)` . And what would happen then? Let’s see for ourselves. If we get an invalidly formatted raw show:

>

val invalidRawShow = "Breaking Bad, 2008-2013"  ①  
parseShow(invalidRawShow)
Exception in thread "main": String index out of range: -1

① The years should be in brackets, but they are not! Note that this is only one of many ways it may fail. We will discuss it shortly.

Not only it does not return a `TvShow` back, it throws an exception and crashes the whole app, too. So our function breaks the promise it gave us with its signature: ``` def parseShow(rawShow: String): TvShow ```

If parseShow was a person, we could be tempted to ask it, “Dear parseShow . It seems you don’t return a TvShow for any String we give you. Why would you lie to us like that? .

Pure functions should not throw exceptions

Our parseShow function throws an exception if a String we give is not properly formatted. This fact alone proves that the parseShow function is not pure—it doesn’t always return a promised value (a TvShow ). How can we solve it? Let’s find out by looking at potential solutions.

In Java, we could use a try...catch and return null if something is thrown, although it’s not a good practice.

Pure function

Returns a single value

Uses only its arguments

Doesn't mutate existing values

``` try { return parseShow(invalidRawShow); } catch(Exception e) { ① return null; } ``` ① We could also throw an exception and let the client worry about it. The problem remains the same: users of this function need to have two ways of handling it, one for proper values and one for exceptions/ `null` s. That means that there will be `if` s and `try` ... `catches` everywhere. This approach makes sure that our application won’t crash if TV shows can be parsed. But what’s the cost of such a solution? ## Is returning `null` a good idea? There are two problems with functions that may return `null` in error cases. Both have an impact on users of our code:
  • The function’s return value does not contain any hint that it may fail (it promises to always return a TvShow , but it sometimes returns null ).

  • Users can’t trust our functions, and they need to protect themselves against possible nulls everywhere!

Let’s put ourselves in our user’s shoes. Let’s try to use a function that returns `null` if the `String` is not formatted correctly. This means that the client code will probably look like this: ``` TvShow show = parseShow(invalidRawShow); ① if(show != null) { // do more things with the show } ``` ① **Very bad ergonomics!**      Instead of focusing on business logic, a developer that uses our function needs to think about two different ways it may behave. This is not a functional way! Signatures always indicate all of the possible return values. **A user always gets a value back!** The `parseShow` signature needs to change: for some `String` s there is no correct `TvShow` . `Option` to the rescue! The good news is that we can solve both of these problems by using the `Option` type we met in the previous chapter! A value with type `Option` can be one of two possible things: an existing value or a nonexisting value. In the previous chapter we learned that `Option` can be used in sequential programs because it has the `flatMap` function. In this chapter we will use this knowledge and treat `Option` as a type that indicates successful and failed computations. Please recall the fact that returning a `None` in one enumerator `flatten` s the whole for comprehension to `None` . The same happened when we `flatMap` ped an empty `List` ! Quick reminder: How does `Option` work? `Option[A]` has two concrete subtypes: `Some[A]` and `None` , meaning that if we want to create a value of type `Option[Int]` we need to choose whether it’s an existing value (e.g., `Some(7)` ) or not ( `None` ). ![](/images/book/grokking-functional-programming/6b02293a-07eb-4a3a-9b4a-f3053d298fc9.png) ``` val existing: Option[Int] = Some(7) val nonExisting: Option[Int] = None ``` There is no other way! To create a value of type `Option` , we need to choose `Some` or `None` . And the most profound thing is that both `Some` and `None` are values—they are both handled the same way. ## How do we handle potential errors more gracefully? ![](/images/book/grokking-functional-programming/f94ccc54-01d6-42e6-ac87-ff77f3332381.png) Let’s try to make the **`parseShow`** function more trustworthy by using the powers of the `Option` type. Our `parseShow` function will return an `Option` -typed value to let a user know whether the parsing succeeded or not. ![](/images/book/grokking-functional-programming/e241dae4-ca84-4551-a886-a3cb19c1a322.png)

We now know that parseShow should return an Option[TvShow] . If you feel a little bit surprised by this, don’t worry, as things should clarify very soon. You may also feel that throwing a checked exception * , which is also visible in a signature, is perfectly fine. However, there are more reasons not to use exceptions than just language mechanics, and we will cover all of them soon. Before we do, let’s focus on our new parseShow .

\* As a reminder, if your function throws a checked exception, it needs to indicate that in the signature by adding a `throws` clause. We will cover this soon, and we will compare this approach with the functional one. No exceptions! As you know, we want to design useful functions that are convenient and safe to use. That’s why we always start from the perspective of its users. So, let’s find out how `Option` -based `parseShow` would be used.

>

parseShow("The Wire (2002-2008)")   → Some(TvShow("The Wire", 2002, 2008))
parseShow("The Wire aired from 2002 to 2008")
→ None
As you can see, when we provide a well-formatted `String` , we get the `TvShow` wrapped in `Some` . For an invalid `String` , we get `None` . ## Implementing a function that returns an `Option` We’ve talked a lot about signatures and how a user would use our `parseShow` function. By looking at the signature, our users know that the `parseShow` function gets a `String` and may return either `Some(TvShow)` \* if the `String` is formatted correctly or `None` if it isn’t. Now it’s time to try to implement `parseShow.` Before we do that, let’s look again at the previous implementation that throws an exception if it gets an invalidly formatted `String` and compare it to the `Option` -based one. \* This is exactly what we want from pure functions. We expect they don’t ever lie to us. Before Returning `TvShow` (or throwing an exception if something goes wrong) ``` def parseShow(rawShow: String): TvShow = { ① val bracketOpen = rawShow.indexOf('(') val bracketClose = rawShow.indexOf(')') val dash = rawShow.indexOf('-') val name = rawShow.substring(0, bracketOpen).trim ② val yearStart = Integer.parseInt(rawShow.substring(bracketOpen + 1, dash)) val yearEnd = Integer.parseInt(rawShow.substring(dash + 1, bracketClose)) TvShow(name, yearStart, yearEnd) ① } ``` ① If `rawShow` doesn’t contain at least one of these separator characters, we will get -1 as one of these values. ② Calling `substring` with -1 will inadvertently end up with a `StringIndexOutOfBoundsException` . ③ We should probably define and throw our own exception here, but the code would get a lot messier, so let's leave it for now. After Returning `Option[TvShow]` (always!) ``` def parseShow(rawShow: String): Option[TvShow] = { for { name <- extractName(rawShow) yearStart <- extractYearStart(rawShow) yearEnd <- extractYearEnd(rawShow) } yield TvShow(name, yearStart, yearEnd) } ```

We yield a TvShow only if all three steps above return a Some . If any step returns None , the whole for comprehension will be None . Note that name is a String , and yearStart and yearEnd are Ints . The <- syntax inside a for comprehension makes sure that if the right-hand side is a Some(value) , we get the bare value on the left-hand side.

→

This function is totally safe. It will always return a value of type Option[TvShow] , no matter what String we give it. That's a promise we get in the signature!

We use a for comprehension to make sure everything is done in the context of Option , evaluated step by step in a sequential manner, like a pipeline. Each step is a function call. Each of these extract functions need to return an Option to satisfy the compiler. We will implement them next. Their signatures are:

def extractName(rawShow: String): Option[String]  def extractYearStart(rawShow: String): Option[Int]
def extractYearEnd(rawShow: String): Option[Int]
Let’s imagine how such a function would be used. We expect that when we give a `String` that cannot be parsed, the whole function returns `None` instead of throwing an exception and crashing. Note that we still don’t have a fully functional solution to the problem. We are just comparing the signatures and usages to obtain an intuition about how `Option` -based differs from exception-based. ``` parseShow("Mad Men (-2015)") → None ``` However, it should return a `TvShow` wrapped in `Some` if the `String` is valid. ``` parseShow("Breaking Bad (2008-2013)") → Some(TvShow("Breaking Bad", 2008, 2013)) ``` ## `Option` forces us to handle possible errors You probably wonder why we introduced small `extract` functions in the `Option` -based version and not in the exception-based version. The short answer is that in the `Option` -based version it really matters, while in the exception-based version it’s just a matter of aesthetics. The longer answer requires us to discuss an important distinction between _being forced to handle an error_ and _being able to handle an error._ ![](/images/book/grokking-functional-programming/120546a0-eb81-4b79-9882-bae8ba3a1f0b.png) ## Building from small blocks When we try to use an `Option` value, we are forced to handle the possibility of it being a `None` . There is no way around this! The same is true for other programming mechanics we will learn in later chapters. For now, we do just the error handling. When we want to write a function that returns a value only for some cases, we indicate it in the signature. ``` def extractName(rawShow: String): Option[String] def extractYearStart(rawShow: String): Option[Int] def extractYearEnd(rawShow: String): Option[Int] ``` THIS IS BIG! Indicating an error in FP means returning an immutable value that represents an error. We can tell exactly what’s going on just by scanning the signature. Of course we don’t know everything because the details of parsing each of the three fields are hidden inside three functions. The cool thing is that even though they are hidden, we can be sure there are no surprises there. These are just pure functions that return immutable values! But there is more! By creating these small functions that return `Option` s, we are setting the pace for everything else in the codebase! We are creating small blocks that can be used to build larger structures but only if the rules that we defined are satisfied! What rules, you might ask? Well, the rules included in the `Option` type, for example. As we have just discussed, when we return an `Option` , we are forcing our clients—users of our code—to handle the possibility of an error! They need to be aware that there is a possibility of `None` . This is the rule that we are enforcing! When we use `Option` , we use `None` as a value that represents an error. We can use other types, too, which we’ll soon see. ![](/images/book/grokking-functional-programming/ba8a842c-cba2-489d-bb99-05b0a186391d.png) ## Functional design is building from small blocks We have already discussed functional design on several occasions. The first rule of functional design is to break the functionality into small blocks of code, which, in our case, are always functions—pure functions. These blocks of code—functions—return immutable values that can be used together in a very specific way to compute another value, which represents a bigger thing. This idea of how well different, independent values can be used together to compute another value is called **composability** . Let’s look at our current example from the perspective of composability. In our case, we have three small functions: `extractName` , `extractYearStart` , and `extractYearEnd` . They all return `Option` s, so we know that to use them, we’ll need to handle both `Some` and `None` cases. We want to build a bigger function that is responsible for parsing a raw TV show, handling all the corner cases that are represented by `Option` s encoded in `extract` functions. The for comprehension we used is one example of that; it composes three different values of `Option` to produce a single output value: an `Option[TvShow]` . ![](/images/book/grokking-functional-programming/35192728-3f5a-4e60-8869-80e7929c49b4.png) Breaking requirements into smaller blocks of code is a very natural approach in functional programming because it’s much easier to achieve than in other paradigms. I know what you are thinking. “Why is this better than checked exceptions?!” Point taken. We will compare this approach to throwing checked exceptions in Java very soon. But before we do it, let’s finish the `Option` -based `parseShow` by implementing the three small remaining `extract` functions, which contain details about extracting data from a raw string. I will show you how to implement the `extractYearStart` and ask you to do the two remaining as an exercise. ## Writing a small, safe function that returns an `Option` Now let’s see how functional design works in practice. We created the `parseShow` function, which is built from smaller blocks. These blocks—smaller pure functions—are not implemented yet. We just know their signatures! We know that they need to return `Option` s because there is a possibility that they won’t be able to extract what we need. We designed the code by creating four signatures ( `parseShow` and three `extract` functions), and we implemented `parseShow` and got proof that these signatures make sense and can work well together. Now that we have the proof that these functions are useful, we can focus on each of these functions independently without assuming anything about the other ones! This is one of the most enjoyable things in functional programming; **the ability to focus on just one thing without worrying about disrupting others** . Let’s implement `extractYearStart` . THIS IS BIG! In FP, you can focus on implementing one small function without worrying about others.

❶

We start with the signature. Our function takes a String and returns an Option[Int]:

``` def extractYearStart(rawShow: String): Option[Int] = { ??? } ```

❷

To get the start year, we need to find separator characters first:
    "TITLE ( START -END)":
bracketOpen ⬏      ⬑ dash

``` def extractYearStart(rawShow: String): Option[Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') ??? } ``` You may worry about rawShow being null here. Here we only use FP concepts like `Option` in the whole codebase, so there’s no need to worry about `null` s. However, if you are integrating with some impure `null` -based codebases, you need to defensively check `null` s and convert them into `Options` , for example.

❸

We know that String.substring can throw an exception, but we want to use Option instead. That’s why we need to call String.substring only when we know it won’t fail:

  
``` def extractYearStart(rawShow: String): Option[Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') if (bracketOpen != -1 && dash > bracketOpen + 1) Some(rawShow.substring(bracketOpen + 1, dash)) else None } ``` Compilation error! `Option[String]` `rawShow.indexOf` returns -1 if a given character can’t be found. We need to be sure that `bracketOpen` is different than -1. We also know that we want to extract a nonempty `String` that needs to exist between `bracketOpen` and `dash` . Thus, we also make sure that `dash` exists further in the `rawShow` than `bracketOpen` . If both conditions are met, we know we can safely call `rawShow.substring` and wrap the value in Some. If at least one of the conditions are not met, we return None without calling `rawShow.substring` and avoiding throwing an exception. **There is still a compilation error, though; we have `Option[String]` but need `Option[Int]`** .

❹

Our signature says that we return an Option[Int], but our implementation returns an Option[String] instead. We need to transform the Option[String] into an Option[Int] :

  
![](/images/book/grokking-functional-programming/83d0bd1a-313e-4140-b75f-759981b0e5f2.png) `yearStrOpt` is a value of type `Option[String]` , which means it can be either a `Some[String]` or a None. We want to transform the String into an Int, but only if yearStr is a `Some[String]` , because we can't do anything with None. It turns out that this is a pattern we learned about in chapters 4 and 5: we need to use a map! If we map over None, the result is None, if we map over a `Some` , the result is `Some` with the value produced by the function we gave to `map` ! ![](/images/book/grokking-functional-programming/68e4e10b-16c7-47cb-b195-e6ff9fc0c0e4.png) What function did we pass to `map` ? In this case we passed the `String.toIntOption` —a Scala addition to Java `String` . It tries to parse an integer value from the given `String` . If it's possible, it returns an `Option[Int]` . If it’s not, it returns a `None` ! And it’s already in the standard library! ``` > "1985".toIntOption > "MCMLXXXV".toIntOption > "".toIntOption → Some(1985) → None → None ``` **The compiler is still not happy: we have `Option[Option[Int]]` , but need `Option[Int]`** .

❺

Our signature says that we return an Option[Int] but our implementation returns an Option[Option[Int]] instead.We need to transform the Option[Option[Int]] into an Option[Int] :

  
``` def extractYearStart(rawShow: String): Option[Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') val yearStrOpt = if (bracketOpen != -1 && dash > bracketOpen + 1) Some(rawShow.substring(bracketOpen + 1, dash)) else None yearStrOpt.map(yearStr => yearStr.toIntOption).flatten } ```                                           **Now it compiles and works as intended** .

❻

Wait! map and flatten ? Doesn’t it sound familiar? It's a flatMap ! And if it’s a flatMap , then it’s a for comprehension:

``` def extractYearStart(rawShow: String): Option[Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') for { yearStr <- if (bracketOpen != -1 && dash < bracketOpen + 1) Some(rawShow.substring(bracketOpen + 1, dash)) else None year <- yearStr.toIntOption } yield year } ``` Our small, pure function is built from even smaller blocks! The first one safely gets a substring, and the second safely parses a `String` to an `Int` ! ## Functions, values, and expressions Let’s use this opportunity to quickly recap the difference between function applications, values, and expressions. In fact, we need to reiterate that there is no practical difference between them in FP. We will see this by using, as an example, the `extractYearStart` that we just wrote. ``` def extractYearStart(rawShow: String): Option[Int] = { ① val bracketOpen = rawShow.indexOf('(') ② val dash = rawShow.indexOf('-') for { ③ yearStr <- if (bracketOpen != -1 && dash < bracketOpen +1) ③④ Some(rawShow.substring(bracketOpen +1, dash)) ③④ else None ③④ year <- yearStr.toIntOption ③⑤ } yield year ③ } ``` ① This is a pure function definition, which will be an expression after applying it to a `rawShow` ! Moreover, this expression will always produce the same value for the same `rawShow` . ② This is a pure function application, which is an expression! The `indexOf('(')` function will always produce the same value for the same `rawShow` . ③ This is a for expression that produces a value, which is always the same for the same `rawShow` . ④ This is an if expression that produces a value, which is always the same for the same `rawShow` . ⑤ This is a pure function application which, is an expression as well. `toIntOption` function will always produce the same value for the same `yearStr` , which will always be the same for the same `rawShow` . The `extractYearStart` can be used in expressions that produce values.

>

extractYearStart("Breaking Bad (2008-2013)")  → Some(2008)

extractYearStart("Mad Men (-2015)")
→ None

extractYearStart("(2002- N/A ) The Wire")
→ Some(2002)
The `extractYearStart` function is applied to different `String` values. These are three expressions that produce values; each value is always the same for the same `String` . In fact, in FP, expressions and values they produce are interchangeable. It’s the real definition of referential transparency we discussed earlier.

Recap: Statements vs. expressions

There is a distinction between a statement and an expression. A statement is a language construct that needs to change the state of a program in order to be useful. In Java, the following is unusable:

if (bracketOpen != -1 && dash > bracketOpen + 1)    rawShow.substring(bracketOpen + 1, dash);
else null;

An expression, on the other hand, always returns something, and, when executed many times, it always returns the same result—a value. In fact, we can even say that the following if expression is a value :

val yearStrOpt = if (bracketOpen != -1 && dash > bracketOpen + 1)
                   Some(rawShow.substring(bracketOpen + 1, dash))
                 else None

THIS IS BIG! FP is programming with expressions; functional programmers don’t use statements. ## Practicing safe functions that return `Option` s ![](/images/book/grokking-functional-programming/f2e85480-b7f6-4d6e-966f-f5ca29402648.png) We designed our new `parseShow` function that gets three pieces of information and produces a `TvShow` , or it bubbles up any error that may have occurred, represented as `None` . We saw how to implement one of these three functions, `extractYearStart` . The bubbling up works thanks to `flatMap` . We will do a quick recap after the exercise.

parseShow

→

extractYearStart

def parseShow(rawShow: String): Option[TvShow] = {    for {
    name <- extractName(rawShow)
    yearStart <- extractYearStart(rawShow)
    yearEnd <- extractYearEnd(rawShow)
  } yield TvShow(name, yearStart, yearEnd)
}
def extractYearStart(rawShow: String): Option[Int] = {
  val bracketOpen = rawShow.indexOf('(')
  val dash        = rawShow.indexOf('-')
  for {
    yearStr <- if (bracketOpen != -1 && dash < bracketOpen + 1)
                  Some(rawShow.substring(bracketOpen + 1, dash))
               else None
    year <- yearStr.toIntOption
  } yield year
}
**Your task is to implement the two missing functions.** Each of them gets a `rawShow String` and returns an `Option` . The return value should be a `Some` in case a particular piece of information can be _extracted_ from the raw TV show and `None` if it can’t due to invalid formatting. More specifically, you need to implement the following two functions: ``` def extractName(rawShow: String): Option[String] def extractYearEnd(rawShow: String): Option[Int] ``` Use the REPL to implement and test both functions. Make sure you test both correctly and incorrectly formatted `Strings` before looking below. Answers

>

def extractName(rawShow: String): Option[String] = {    val bracketOpen = rawShow.indexOf('(')
  if (bracketOpen > 0)
    Some(rawShow.substring(0, bracketOpen).trim)
  else None
}

def extractYearEnd(rawShow: String): Option[Int] = {
  val dash         = rawShow.indexOf('-')
  val bracketClose = rawShow.indexOf(')')
  for {
    yearStr <- if (dash != -1 && bracketClose > dash + 1)
                 Some(rawShow.substring(dash + 1, bracketClose))
               else None
    year <- yearStr.toIntOption
  } yield year
}
1 We get the index of the bracket. If it’s found, we return `Some` with the name inside. If not, we return `None` . 2 We get the index of the dash and closing bracket. If they are found, and the closing bracket is further in the `String` than the dash, we can safely call the `substring` function and pass the `String` to the next phase, which parses the integer. ## How do errors propagate?

As you’ve seen , the functionality of parsing a raw TV show is implemented using four very small functions. All of them return an Option value, and since Option includes a flatMap function, it can be used inside for comprehensions. We are focusing on the happy path, but we can be sure that if anything goes wrong (i.e., any function returns a None value), the None value will be bubbled up to the topmost function and returned as a result of the whole computation, indicating that parsing was not successful. In short, we are discussing short-circuiting .

You may wonder, how does it all work? Is it Scala-specific or Option -specific? It turns out it’s neither. It is flatMap specific! We already learned about flatMap before, but this time we are in the context of error handling, and it needs to be reiterated. Let’s see how it works.

Short-circuiting is a programming concept that allows skipping evaluation of some expressions if a specific condition is met. Here, extractYearEnd won’t be evaluated if extractName returns None .

![](/images/book/grokking-functional-programming/ad8fc065-75da-4dbb-80c1-b9d0daf0808b.png) ![](/images/book/grokking-functional-programming/52351fb5-c41c-4724-b820-8a68e3969781.png) ![](/images/book/grokking-functional-programming/b5e817c0-fafe-4250-894c-9a206ddbf638.png) ## Values represent errors Note that even though we talk about handling errors, we don’t really throw or catch any exceptions. We operate only on values; `parseShow` is a pure function \* that gets a value and returns a value. `flatMap` is a pure function that gets an `Option` and a function and returns an `Option` . And because for comprehensions are just a syntactic sugar for `flatMaps` , the same applies to them; a for comprehension is an expression that produces a value. \* `flatMap` gets two arguments: one is the `Option` we are calling `flatMap` on, and the second is the function that returns an `Option` .

>

def parseShow(rawShow: String): Option[TvShow] = {    for {
    name      <- extractName(rawShow)      ①
    yearStart <- extractYearStart(rawShow) ①
    yearEnd   <- extractYearEnd(rawShow)   ①
  } yield TvShow(name, yearStart, yearEnd) ①
}

① An expression that produces a value of type Option .

![](/images/book/grokking-functional-programming/616bb4ee-4ea5-44c3-bc7f-4de1b9f3d742.png) Again, a very important thing is that the returned `Option` **type conveys information about a potential error** . And it does it by explicitly making it part of its signature! No surprises here—pure function for the win! Quick exercise: Analyzing values ![](/images/book/grokking-functional-programming/943cbd62-42ea-4543-a7f7-40d0dc8bb4e8.png) Before we move on and try to compare this technique with throwing and catching exceptions, we need to make sure you understand that all we’ve been doing here is calling pure functions that get and return immutable values and that even errors are represented by immutable values. So now **it’s your turn to parse some TV shows** ! In your head, execute the `parseShow` function shown above for the following three `Strings` , noting the return value: - “Stranger Things (2016-)” - “Scrubs (2001-2010)” - “Chernobyl (2019)” Values, values everywhere

This may be a paradigm shift for you. But, hopefully, you are getting the feel for the functional programming style. In the previous chapter we represented sequential programs as a sequence of pure function calls on immutable values. Now, we represent failures as values, but programs are still just sequences of pure function calls. It’s surprising how powerful this idea really is and how much more we can do with it! Soon, you will acquire error handling superpowers by passing more descriptive values!

Answers: `None,` `Some(TvShow(`     `"Scrubs",`     `2001,`     `2010)),` `None` ## `Option` , for comprehensions, and checked exceptions ...

OK, Option looks nice, but how exactly is it better than plain-old throws Exception in Java? Why should we prefer Option ?

That’s a great question, we will get our answer in the following pages. But before we move on, let’s quickly gain some perspective on where we are in our journey to learn functional error handling!

![](/images/book/grokking-functional-programming/652c9722-cddc-4288-aa93-05fbe3388c55.png) Now, let’s go back to our `parseShow` function and try to reimplement it in Java using checked exceptions. Will there be any difference? Is functional error handling really better? Let’s find out by looking at some code! ## What about checked exceptions? So how exactly is the `Option` approach better than checked exceptions? We will answer that by looking at some Java code that parses a raw TV show `String` and uses exceptions to indicate problems. Note that we will still want to use the same code structure with small units responsible for extraction of name and years. The only difference is that instead of `Option` we’ll use `Exception` -based error handling. We need to rewrite four functions: `extractName` , `extractYearStart` , `extractYearEnd` , and, finally, `parseShow` . Here we will just show the implementation of `extractName` and `parseShow` because the two remaining `extract` functions look similar to `extractName` .

Functional

  

Imperative

def extractName(rawShow: String): Option[String] = {    val bracketOpen = rawShow.indexOf('(')
  if (bracketOpen < 0)
    Some(rawShow.substring(0, bracketOpen).trim)
  else None
}

→

public static String extractName(String rawShow) throws Exception {
  int bracketOpen = rawShow.indexOf('(');
  if(bracketOpen < 0)
    return rawShow.substring(0, bracketOpen).trim();
  else throw new Exception();
}

To be equivalent, the Java version needs to explicitly throw a checked Exception when parsing is not possible.

def parseShow(rawShow: String): Option[TvShow] = {
for {
  name        <- extractName(rawShow)
    yearStart <- extractYearStart(rawShow)
    yearEnd   <- extractYearEnd(rawShow)
  } yield TvShow(name, yearStart, yearEnd)
}

→

public static TvShow parseShow(String rawShow) throws Exception {
  String name   = extractName(rawShow);
  int yearStart = extractYearStart(rawShow);
  int yearEnd   = extractYearEnd(rawShow);
  return new TvShow(name, yearStart, yearEnd);
}

  

  

Note that probably the best approach would be to define a custom checked exception, but Exception should be suficient for demonstration purposes.

Q Wait! It looks exactly the same! Why are we looking at `Option` s when `Exception` s can do exactly the same thing? A That’s true. Assuming that we use checked exceptions, the compiler makes sure that all the errors are either handled or present in the signature. However, when requirements get a little more complicated (and they always do!), our exception-based solution blows up while the functional one stays almost the same. Interested? ![](/images/book/grokking-functional-programming/f91e1fb7-c1d8-448d-a931-79220ba2d2ca.png) Let’s add one small requirement to show how graceful the functional error handling really is (as compared to the imperative type). ## Conditional recovery So far we haven’t seen any practical difference between `Option` -based FP solutions and exception-based solutions. They looked and worked pretty much the same. No matter if we constrain ourselves to using only checked exceptions or `Options` , we get exactly the same benefits: 1. Both signatures don’t lie, they tell what they return, and they tell that they may fail without any result. 2. Both functions don’t crash their whole applications, and they make sure all possible errors are handled somewhere else (by one of their clients). A big difference appears when we try to implement branches that evaluate different code paths based on a possible error. Code that is executed in case of an error is called _recovery code_ \* . The whole process is called **conditional recovery,** and you’ve probably dealt with many cases of it. Let’s see an example by introducing yet another requirement. \* If we have a branch in a function, it means there are at least two possible different code flows. If a branch is related to an error, one code flow is needed to handle this error. New requirement: Some shows may have only one year Some TV shows have just one season, and they are represented as a raw `String` in the following format: `TITLE (YEAR)` . For example: ``` val singleYearRawShow = "Chernobyl (2019)" ``` For simplicity, let’s assume that in this case, our function should return `Some(TvShow("Chernobyl", 2019, 2019))` . What matters here is that it should return a successfully parsed TV show for both cases: single-year shows and the ones that aired for multiple years. Naturally, the current version of `parseShow` doesn’t follow the expected format, and the function would return `None` (or an exception in the imperative version). What happens if we try to parse it using our `Option` -based `parseShow` ? ``` parseShow("Chernobyl (2019)") → None ``` Similarly, the exception-based version throws an `Exception` : ``` parseShow("Chernobyl (2019)") → Exception in thread "main" Exception ``` We expected that. Our task is to add this new functionality—and keep the current functionalities intact—to both versions and then compare again. We’ll start with the exception-based code. Take a moment to think about a possible solution before moving on. ## Conditional recovery using the imperative style The pseudocode of the logic we want to implement looks like this. ![](/images/book/grokking-functional-programming/bcd1823e-8fc5-4aaa-a826-1ebf1481cb7e.png) If we can’t parse the start year, we need to recover this error by falling back to a single-year case. The same thing happens with the end year. \* \* Note we could optimize this code a bit in this case by not recalculating single year twice but the main conclusion would not change. To fall back to parsing a single year, we need to try parsing the start year first, and we need to know if it failed or not. The only way to do that in the exception-based code is using the `try...catch` syntax. ```java public static TvShow parseShow(String rawShow) throws Exception { String name = extractName(rawShow); Integer yearStart = null; try { yearStart = extractYearStart(rawShow); ① } catch(Exception e) { yearStart = extractSingleYear(rawShow); ② } Integer yearEnd = null; ③ try { yearEnd = extractYearEnd(rawShow); } catch(Exception e) { yearEnd = extractSingleYear(rawShow); } return new TvShow(name, yearStart, yearEnd); } ``` ① We need to first try to get the start year. ② After we catch the `Exception` we know that the start year can’t be parsed, and we can try to extract the single year. ③ We need to initialize `yearStart` and `yearEnd` to `null` , which makes the code even more unreadable. Note we still need to implement a new function, `extractSingleYear` . It will look very similar to other `"extract"` functions, so let’s not focus on it here. Remember that for `"Chernobyl (2019)"` we are falling back to single-year case for both start year and end year. Thus, we get a `TvShow("Chernobyl", 2019, 2019)` . Well, this blew up, as promised! Compare the pseudocode with the code above and how much complication we needed to introduce to handle the conditional recovery for exception-based code. ## Conditional recovery using the functional style ![](/images/book/grokking-functional-programming/6db5eb07-1d15-4082-befd-964876bebb59.png) We’ve seen the imperative solution using exception-based code. It works, but it adds some complexity to the code, which in turn affects the maintainability. Remember that the code is read far more often than written, so to improve maintainability, we need to make the code as easy to read as possible. (That also means that we need to write boring code.) I know that I repeat myself here, but it’s really important. Boring code is good code. Writing boring code is hard. But it pays off! OK, enough with this pep talk—let’s see some code! If Java exception-based code is so complicated and not maintainable, how will the FP solution look? In FP, everything is an immutable value, so we don’t really need any special syntax. **We just need a new pure function** . Conveniently, `Option` already has a function named `orElse` .

>

def parseShow(rawShow: String): Option[TvShow] =    for {
    name <- extractName(rawShow)
    yearStart <- extractYearStart(rawShow).orElse(extractSingleYear(rawShow)) ①
    yearEnd <- extractYearEnd(rawShow).orElse(extractSingleYear(rawShow))
  } yield TvShow(name, yearStart, yearEnd)                                    ②

① extractYearStart returns a value of type Option, so we can call orElse on it and get another value of type Option back!

② Find the extractSingleYear implementation below.

No, that’s not pseudocode. **It’s a compiling piece of Scala code.** It correctly implements our requirement! `orElse` is just another function defined on `Option` , like `map` , `flatMap` , and others. **We will explain how** `orElse` **works very soon** . For now, just treat it as yet another pure function that helps us implement conditional error handling and recovery far better than exceptions. THIS IS BIG! In FP, there usually is a function for every problem in your code. Does it really work as intended? Have a look for yourself.

>

def extractSingleYear(rawShow: String): Option[Int] = { ①    val dash = rawShow.indexOf('-')
  val bracketOpen = rawShow.indexOf('(')
  val bracketClose = rawShow.indexOf(')')
  for {
    yearStr <- if (dash == -1 && bracketOpen != -1 && bracketClose > bracketOpen + 1)
                   Some(rawShow.substring(bracketOpen + 1, bracketClose))
               else None
    year <- yearStr.toIntOption
  } yield year
}

parseShow("Chernobyl (2019)")
→  Some("Chernobyl", 2019, 2019)
parseShow("Breaking Bad (2008-2013)")
→  Some("Breaking Bad", 2008, 2013)
parseShow("Mad Men (-2015)")
→  None ②

① We need to finally implement the extractSingleYear function that handles the new requirement. Nothing interesting here, it's very similar to other examples.

② Everything works like a charm! We were able to implement the new requirement without any big changes in our original function. It’s because we didn’t need a new syntax—just a new function.

![](/images/book/grokking-functional-programming/e4fe1fde-7002-406c-9b20-454f387814bc.png) ## Checked exceptions don’t compose— `Options` do! The main difference between checked exceptions and functional error handling is that checked exceptions don’t compose, while functional handlers compose very well. Functions and values compose well When we say that something composes well, we mean that we are able to easily combine two small things to build a larger one. For example, when you have two small, independent pure functions that return an `Option` , you can compose them together into a bigger function that handles more cases by calling just one function ( `orElse` ): ``` extractYearStart(rawShow).orElse(extractSingleYear(rawShow)) ``` That’s how easy it is to compose `extractYearStart` and `extractSingleYear` functions into a bigger function. THIS IS BIG! Functions and values compose very well together—we use them to build big programs from smaller pieces. Imperative code doesn’t compose well ![](/images/book/grokking-functional-programming/f91e1fb7-c1d8-448d-a931-79220ba2d2ca.png) In the imperative approach, if you want to make a decision based on whether some particular piece of code failed or not, you need to explicitly catch the exception and execute follow-up code. ``` Integer yearStart = null; try { yearStart = extractYearStart(rawShow); } catch(Exception e) { yearStart = extractSingleYear(rawShow); } ``` To compose two functions that can throw exceptions, we need to explicitly catch those exceptions and specify the exact steps the program needs to take to recover properly. Exceptions can only be handled imperatively. The amount of `try..catches` grows very quickly. It hit us when we tried to use just one level of branching! Imagine what would happen if you needed to make another decision based on another failure (e.g., what happens if the year is provided in the `2008-13` format?). We will explore such scenarios later in the chapter, but rest assured that functional programming has us covered. **We will use function composition to our advantage** not only in advanced error handling but also in side-effectful programming, multithreading, and testing later in the book! ## How does `orElse` work?

We now know the benefits of the functional approach to error handling. In FP we create new immutable values based on immutable values by using pure functions. Using checked exceptions, we need to run the code, * see if it fails, and run another piece of code based on that. Again, that’s yet another example of our declarative programming versus imperative programming discussion. The declarative approach focuses on defining relationships between values, whereas imperative tries to implement step-by-step recipes for how the program should be executed by the computer.

\* It’s probably getting repetitive by now. We’ve been talking about immutable values and pure functions since chapter 2. It’s repetitive because this whole book is about pure functions and immutable values. We can do plenty of things with them! `orElse` is a perfect example of a pure function that takes two immutable values and produces another immutable value. It’s also a perfect example of defining relationships between values.

>

val seven: Option[Int] = Some(7)  val eight: Option[Int] = Some(8)
val none: Option[Int] = None

seven.orElse(eight)
→ Some(7)        ①
none.orElse(eight)
→ Some(8)        ②
seven.orElse(none)
→ Some(7)        ③
none.orElse(none)
→ None           ④

① The first Option is Some , so return it.

② The first Option is None , so return the second one, no matter what it is.

③ The first Option is Some , so return it.

④ The first Option is None , so return the second one, no matter what it is.

THIS IS BIG! Handling errors in FP is taking an error value and returning a different value. ![](/images/book/grokking-functional-programming/d02ea772-7838-41f0-8c4c-f4398f34342e.png) In our case it’s a relationship between values that represent a potential parsing problem. What `orElse` does in this case is **describe the error handling** !

>

val chernobyl = "Chernobyl (2019)"   extractYearStart(chernobyl)
→ None 
extractSingleYear(chernobyl)
→ Some(2019)

extractYearStart(chernobyl).orElse(extractSingleYear(chernobyl))    ①
→ Some(2019)
extractYearStart(chernobyl).orElse(extractSingleYear("not-a-year")) ①
→ None

① The first Option is None , so return the second one, no matter what it is.

## Practicing functional error handling ![](/images/book/grokking-functional-programming/f2e85480-b7f6-4d6e-966f-f5ca29402648.png) We designed our new `parseShow` function that gets three pieces of information and produces a `TvShow` . The three pieces of information are extracted using small functions that return `Options` to indicate a potential success or parsing problem. They are then composed into a bigger function that parses a `String` and returns an `Option[TvShow]` . It is able to handle some potential errors and recover from some of them using `orElse` . We already know how `parseShow` is implemented, but let’s try to practice some different error-handling scenarios using the same set of small functions we’ve implemented so far. ``` def extractName(rawShow: String): Option[String] ① def extractYearStart(rawShow: String): Option[Int] def extractYearEnd(rawShow: String): Option[Int] def extractSingleYear(rawShow: String): Option[Int] ``` ① If you don’t have the previous REPL session open, it’d be beneficial to reimplement these three functions first. **Your task is to implement the following scenarios** by composing the aforementioned functions. Make sure to test different `String` s: `"A (1992-)"` , `"B (2002)"` , `"C (-2012)"` , `"(2022)"` , `"E (-)"` . We have just implemented this one after receiving the new `"TITLE (YEAR)"` requirement. 1. Extract a single year, and if it fails, extract an end year. 2. Extract a start year, and if it fails, extract an end year. If this fails as well, fall back to extracting a single year. 3. Extract a single year only if a name can be extracted. Hint: This one doesn’t need `orElse` ! It needs a different function that we’ve already learned about earlier in the book. 4. In case a name exists, extract a start year, and if it fails, extract an end year. If this fails as well, fall back to extracting a single year. Answers
def extractSingleYearOrYearEnd(rawShow: String): Option[Int] =    extractSingleYear(rawShow).orElse(extractYearEnd(rawShow))

1

This requirement is similar to what we’ve been doing with orElse .

def extractAnyYear(rawShow: String): Option[Int] =
  extractYearStart(rawShow)
    .orElse(extractYearEnd(rawShow))
    .orElse(extractSingleYear(rawShow))

2

More complicated cases can be implemented by sticking yet another orElse at the end.

def extractSingleYearIfNameExists(rawShow: String): Option[Int] =
  extractName(rawShow).flatMap(name => extractSingleYear(rawShow))

3

The function passed to flatMap is executed only if Option is Some .

def extractAnyYearIfNameExists(rawShow: String): Option[Int] =
  extractName(rawShow).flatMap(name => extractAnyYear(rawShow))

4

Functions compose well together! We use this superpower here!

## Functions compose, even in the presence of errors

I hope you already start seeing and appreciating the pattern. Throughout this book, we are learning how to think differently about problems we encounter. We learn that everything is just a value that we can take and return another one back. That’s the essence of functional programming. We have already learned, in chapter 5, that we can represent sequential programs using values. Later in the book we will model full requirements as values (chapter 7) and even represent IO-based and concurrent programs as values! They will all use the same pattern: get an immutable value and create another one inside a pure function. map , flatten , flatMap , filter , foldLeft , and orElse are all examples of this pattern, and there are more yet to come.

In this chapter we learn that we can represent errors as values. `Option` is just a beginning; there are more ways of doing that. We have just discovered that using the functional approach is better because the small functions compose well together to form bigger functions, even in the presence of errors. The same cannot be said about exceptions. ![](/images/book/grokking-functional-programming/f65c96f2-0819-4f70-9bd9-750f699d722c.png) Now, it’s time to level up our error-handling skills and start handling multiple errors at once. What do we mean by that? We’ve focused on parsing a single TV show and already dealt with multiple possible problems, such as missing name, missing year, and so on. The next problem, however, is exactly the same but multiplied by the amount of raw `String` s in the incoming `List` . Remember that the original requirement was to parse a `List[String]` and give a `List[TvShow]` back: ``` def parseShows(rawShows: List[String]): List[TvShow] ``` We know it’s not that straightforward because there are many corner cases. But how difficult could it be? Let’s find out! Next Step **Handling many errors at onc** . Defining higher-order functions that handle many errors using code that handles just a single error. ## Compiler reminds us that errors need to be covered We were able to parse one particular TV show functionally by creating a pure function that takes a `String` and returns an `Option[TvShow]` : ``` def parseShow(rawShow: String): Option[TvShow] ① ``` ① Note that we are using two similar function names. The function that parses one TV show is called `parseShow` , and the one that parses a list of TV shows is called `parseShows` . We now know it works well and is built from smaller, independent pure functions. However, please remember that, originally, we were tasked with a much bigger requirement— **we wanted to parse lists** . Original requirement recap: Parse a list of TV shows Our application gets a **list of raw TV shows** . Each raw TV show is just a `String` that should be in a specific format: `TITLE (YEAR_START-YEAR_END)` or `TITLE (YEAR)` (added later). For example:

>

val rawShows = List("The Wire (2002-2008)", "Chernobyl (2019)")  parseShows(rawShows)
→ List(TvShow("The Wire", 2002, 2008), TvShow("Chernobyl", 2019, 2019))
We already implemented `parseShows` using `map` , but it was back in the days when we used the imperative `parseShow` version, which changed since then. However, the current version doesn’t compile. Before Returning `TvShow` or throwing an exception if something goes wrong ![](/images/book/grokking-functional-programming/c52a550c-9cbf-441f-9ea6-201d45186d23.png) Now Returning a `Some[TvShow]` or `None` if something goes wrong ![](/images/book/grokking-functional-programming/17f5b476-e094-4296-961f-f2133750afa1.png) ## Compilation errors are good for us! The problem is subtle: the compiler does not like what it sees. `parseShow` returns an `Option[TvShow]` , so if we are mapping over a list of `String` s, we’ll get a `List[Option[TvShow]]` , not the `List[TvShow]` that is indicated in the signature. This results in the compilation error!                                                    ![](/images/book/grokking-functional-programming/5c231f94-774e-4e3f-9f31-3c3b2f33f61d.png) Q I hate compilation errors! Why can’t things just work? Does functional programming mean that I will encounter more compilation errors? A Yes! Programming functionally usually means that we encounter more compilation errors. However, the benefit is that we will also get fewer runtime errors! We argue that handling compilation errors is less stressful than handling runtime errors. We’ll see this in action in the remaining parts of this book. THIS IS BIG! In FP, we prefer compilation errors over runtime crashes. From this point on, we start treating our compiler as a friend, not a foe. It will help us a lot by making sure we cover all our bases. Let’s see what exactly our new friend—the compiler—is telling us right now. ![](/images/book/grokking-functional-programming/4cc007cc-a874-4854-94db-ba3b5c4780ba.png) ![](/images/book/grokking-functional-programming/1e27ad3f-f6e1-4a1b-aa06-898f4dcfdcbc.png) See? Nothing scary! Maybe the compiler is a bit passive-aggressive sometimes, but let’s assume it has only good intentions and just tries to help us avoid runtime exceptions popping up in production. ## Transforming a `List` of `Option` s into a flat `List` In functional programming, we work with values, and therefore, we can easily transform one value into another. We have just learned about `orElse` defined on `Option` s. There had been many before ( `map` , `flatten` , `flatMap` , `foldLeft` , `filter` , and `sortBy` ), and there are still many more to come. The standard library gives us lots of built-in pure functions that take immutable values and return some new ones. Whenever you have a problem like “How do I transform X into Y?” you should first look at what’s already at your disposal. **In this case you are looking for** `toList` . Whenever you feel that a value you work with can be transformed into a `List` in a straightforward manner, you can probably do it by calling `toList` on it! In our case, we are working with an `Option` , which can be either `None` or `Some` . Therefore, it can be transformed into a `List` without losing any information. That’s why `Option` has a `toList` function built in. If you call it, you will get either an empty `List` (if the `Option` is `None` ) or a one-element `List` (if it is `Some` ).

>

Some(7).toList  →List(7)

None.toList
→List()
![](/images/book/grokking-functional-programming/ac6216e9-2641-446d-a93a-e677680d8720.png) Now, we can use this information to modify our `parseShows` function and see what the compiler has to say this time. ![](/images/book/grokking-functional-programming/21213c33-3737-483b-8573-dd480ff5b5be.png) ## Let the compiler be our guide ... Our new friend—the compiler—tells us that we are not there yet. In the signature we want to promise that we return a `List[TvShow],` but our implementation returns a `List[List[TvShow]]!` Again, this is a problem of a familiar nature: “How do I transform X into Y?” How do we transform a `List[List[TvShow]]` into a `List[TvShow]` ? There are many possible solutions, but we know one of them particularly well. **It is `flatten`** . We used `flatten` in chapter 5 mostly in tandem with `map` (they both define the `flatMap` function ). But it is a normal standalone function that can be used explicitly, like here! ![](/images/book/grokking-functional-programming/28d5ef1d-e111-4f97-939d-949761d9f01c.png) ![](/images/book/grokking-functional-programming/6c5fd824-8bef-4779-96ee-002347a393d8.png) Using `flatten` should finally make the compiler happy. Let’s see. ![](/images/book/grokking-functional-programming/bd15ed35-441a-417c-a0a9-e100bafd424c.png)

We did it! The code compiles, and we are able to parse multiple shows without any exceptions and without crashing the application. We let the compiler guide us, and we ended up with a sequential program. However, please give this solution yet another thought. Did we ignore something? Were we allowed to ignore it?

Can you replace the map/flatten combo with a flatMap call ?

## ... but let’s not trust the compiler too much!

We were able to implement the requirement: our function gets a list of Strings and returns a list of valid TV shows. We trusted the compiler to guide us in implementing the logic for handling lists of shows. But we need to remember that the compiler works in a purely mechanical way! It doesn’t have the context of the feature we implement. That’s our job! Anytime we let the compiler guide us, we need to control and verify that it’s really what we want. Let’s go back to our example. We have a sequential program.

![](/images/book/grokking-functional-programming/83b0a7f2-aec6-4bf3-a374-448ec57f3c97.png) We met many sequential programs in chapter 5. At its core, the one we are dealing with right now is very similar to them. That’s great, we are trying to tap into exactly the same intuition! From the mechanical perspective, error handling is very similar to sequential programs. We use many pure functions that transform immutable values, usually `map` s, `flatMaps` (or for comprehensions), `filters` , and so on. \* Let’s keep that in mind and build our new error-handling intuition on top of that. \* To be more precise, all the techniques in functional programming are similar: it’s always a bunch of pure functions that transform immutable values! So what did we ignore while we were listening to the beautiful voice of the compiler and blindly following its guidance? Let’s run the code: ``` val rawShows = List("Breaking Bad (2008-2013)", "The Wire 2002 2008", "Mad Men (2007-2015)") parseShows(rawShows) → List(TvShow("Breaking Bad", 2008, 2013), TvShow("Mad Men", 2007, 2015)) ```

What happened? We had a list of three raw shows, but one of them was using an invalid format. Good thing this didn’t crash our app. One thing that may bother us, however, is that we got only two TvShow values back and no information about the invalidly formatted String whatsoever ! By using toList and flatten , we made sure that all Nones were ignored without affecting the rest of the result. It may or may not be what you want, and this is something that we, as developers, need to decide . The compiler will not help us. Our current solution works in the best-effort mode—it returns only TV shows that are parsed correctly. Another approach would be to indicate a possible error within the parseShows signature! This is something we will implement next.

## Coffee break: Error-handling strategies ![](/images/book/grokking-functional-programming/88b0d64e-9f60-451a-98f7-a43eefe9450e.png) We’ve just implemented the _best-effort_ error-handling strategy in the `parseShows` function. It’s time to discuss more strategies. We’ll implement the _all-or-nothing_ error-handling strategy next. To do that, we’ll need a little helper function, and I am asking you to implement it. **Your task is to implement the** `addOrResign` **function defined a** . ``` def addOrResign( parsedShows: Option[List[TvShow]], ① newParsedShow: Option[TvShow] ): Option[List[TvShow]] ``` ① All-or-nothing error-handling logic means that if we have a list of parsed shows, then we can add a new show to it but only if we can parse it. If we can’t parse a new show ( `None` ), then we fail the whole thing by returning `None` .

This looks like a head scratcher, so let’s focus on the signature alone before implementing anything. Please have a look at this signature, and try to come up with the intention behind it. The best way to approach such dilemmas is to execute a function with some random arguments, and try to come up with a sensible answer in your head. In your opinion, what should the result of the following executions be ?

1

```sql addOrResign(Some(List.empty), Some(TvShow("Chernobyl", 2019, 2019))) → ??? addOrResign(Some(List(TvShow("Chernobyl", 2019, 2019))), Some(TvShow("The Wire", 2002, 2008))) → ??? addOrResign(Some(List(TvShow("Chernobyl", 2019, 2019))), None) → ??? addOrResign(None, Some(TvShow("Chernobyl", 2019, 2019))) → ??? addOrResign(None, None) → ??? ```

If you managed to come up with some sensible results for the function executions above, the second part of this exercise should be a little bit easier. However, if not, fear not, and try to implement the function by satisfying the compiler. You get two Options as parameters, and you need to return one Option back. You need to implement addOrResign by merging these two Options you get as parameters and return the result. It can be challenging, so please take your time.

2

Hint Maybe try to implement this function as a sequential program that has two steps, and if any of them fails, the whole program fails. Don’t look here if you haven’t spent a good amount of time thinking about a solution. ## Coffee break explained: Error-handling strategies ![](/images/book/grokking-functional-programming/88b0d64e-9f60-451a-98f7-a43eefe9450e.png) Let’s try to answer the imaginary function executions first and try to come up with the intuition behind this function before trying to implement it, keeping in mind that we are implementing an _all-or-nothing_ error- handling strategy. If any show can’t be parsed, we return an error. ```sql addOrResign(Some(List.empty), Some(TvShow("Chernobyl", 2019, 2019))) ① → Some(List(TvShow("Chernobyl", 2019, 2019))) addOrResign(Some(List(TvShow("Chernobyl", 2019, 2019))), ② Some(TvShow("The Wire", 2002, 2008))) → Some(List(TvShow("Chernobyl", 2019, 2019), TvShow("The Wire", 2002, 2008))) addOrResign(Some(List(TvShow("Chernobyl", 2019, 2019))), None) ③ → None addOrResign(None, Some(TvShow("Chernobyl", 2019, 2019))) ④ → None addOrResign(None, None) ⑤ → None ``` ① We have an empty list of shows, and the new show has been parsed. ② We have an existing list of shows, and the new show has been parsed. We expect to get a new list with two shows back. ③ We have an existing list of shows, and the new show couldn’t be parsed. We get an error. ④ We don’t have a list of shows, so a newly parsed show can’t be added. We get an error. ⑤ We don’t have a list of shows, and the new show couldn’t be parsed. We get an error. As you can see, `addOrResign` is responsible for adding a newly parsed show to the existing list of parsed shows, but only if this list _exists_ (i.e., we haven’t encountered any errors before). Even then, `addOrResign` resigns by returning `None` if a new show couldn’t be parsed. We will use this function later in the chapter, but hopefully, you already have a sense for it. If not, you were probably able to follow the compiler and do the mechanical implementation that more or less satisfies the test cases above. If at least one of the parameters is `None` , return `None` . If both are `Some` , append a new show to the existing list and return a `Some` of this newly created list. If for comprehensions and `flatMaps` rang a bell when you were implementing this exercise, your job became easy.

>

def addOrResign(    parsedShows: Option[List[TvShow]], 
  newParsedShow: Option[TvShow]): Option[List[TvShow]] = {
    for {
      shows      <- parsedShows        ①
      parsedShow <- newParsedShow      ②
    } yield shows.appended(parsedShow) ③
}

① If parsedShows is Some , take the “inside” list, and save it as shows . If it’s None , return None immediately.

② If newParsedShow is Some , take the “inside” parsed show, and save it as parsedShow . If it’s None , return None immediately.

③ Append the new show, and return the result in Some .

I hope you’ve enjoyed this exercise! It was meant to be challenging, as it required incorporating concepts we learned earlier in the book. ## Two different error-handling strategies ![](/images/book/grokking-functional-programming/b6e6211e-e28e-4833-a8a1-0e0b065771bc.png) There are two error-handling strategies that we’ve shown in this chapter based on the `parseShows` example, where we parse multiple `Strings` : - Best-effort strategy - All-or-nothing strategy Note that there are many more possible strategies, which we won’t focus on here. The important thing is that you will need to choose the best one for each particular business case. What we want to show here is that each of these is possible to implement using the functional approach, where we _only_ use immutable values to create new immutable values. Let’s see how these strategies can be implemented in `parseShows` . Best-effort error handling We’ve implemented `parseShows` using the best-effort strategy. ``` def parseShows(rawShows: List[String]): List[TvShow] = { rawShows // List[String] .map(parseShow) // List[Option[TvShow]] .map(_.toList) // List[List[TvShow]] ① .flatten // List[TvShow] } ``` ① // `or: .flatMap(_.toList)` It’s a very concise implementation. It uses `parseShow` to do its job (which, in turn, uses smaller functions!), but if we started using it with real data, we’d quickly find out that getting a `List` that contains only some of the shows we wanted to parse may be frustrating.

>

parseShows(List("Chernobyl [2019]", "Breaking Bad (2008-2013)"))  → List(TvShow("Breaking Bad", 2008, 2013))  ①
parseShows(List("Chernobyl [2019]", "Breaking Bad"))
→ List()                                    ①

① We need to compare the size of the incoming list with the size of the result to know if something went wrong. And even then we don’t know which item caused problems and why!

Best-effort means that we try to parse every raw TV show from the incoming list, and we return only the ones that are valid, ignoring invalid ones. All-or-nothing error handling We could implement `parseShows` using the all-or-nothing strategy. This needs to be encoded in the signature. How? By using `Option` again! ``` def parseShows(rawShows: List[String]): Option[List[TvShow]] ``` Our approach changes and the signature needs to change as well. We will implement this new `parseShows` version next, but I hope you have some idea of how to implement it because you have just done a majority of the work inside `addOrResign` you implemented in the last exercise! All-or-nothing means that we try to parse every raw TV show from the incoming list, and we return the list of parsed shows only if all are valid. ## All-or-nothing error-handling strategy Let’s reimplement `parseShows` using the _all-or-nothing_ strategy. Before we do, let’s revisit the signature, and try to understand it: ``` def parseShows(rawShows: List[String]): Option[List[TvShow]] ① ``` ① Note again that in the previous version, `parseShows` returned a `List[TvShow]` , and if something failed, it was not returned on this list. This was the best-effort strategy. The signature tells us that we can get one of two values: - `None` if at least one raw TV show `String` was invalid (couldn’t be parsed) - `Some[List[TvShow]]` if everything went well and we parsed all shows That’s all we need. To check whether your intuition works correctly for this problem, let’s do a quick exercise. Quick exercise

Your task is to guess what the result of calling the all-or-nothing version of parseShows in the three cases below should be .

Answers in discussion.

``` parseShows(List("Chernobyl (2019)", "Breaking Bad")) parseShows(List("Chernobyl (2019)")) parseShows(List()) ``` Implementing _all-or-nothing_ strategy in `parseShows` Functional programmers solve these kinds of quick exercises all the time. We first create a signature and then try to run it in our head by providing an input and thinking about the output. \* The quick exercise above probably caused you at least one headache. What should we return when we get an empty list as an input? Let’s see: \* If it sounds familiar to you, then you probably know about test-driven development. We first define the test by calling an unimplemented function and asserting its output. Then, we implement the function and rerun the test to check if it works. More about this is to come in chapter 12!

>

parseShows(List("Chernobyl (2019)", "Breaking Bad"))  → None
parseShows(List("Chernobyl (2019)")) 
→ Some(List(TvShow("Chernobyl", 2019, 2019)))
parseShows(List()) 
→ Some(List())    ①

① None means that at least one raw String was invalid. Some means that all raw String s were valid and it returns parsed TV shows. That’s why when we get an empty List , we return a successful Some of empty list back.

OK, let’s try to implement this new version, at least as pseudocode. ![](/images/book/grokking-functional-programming/02a98216-bab2-4434-a7d9-5e1a5c17488d.png) ## Folding a `List` of `Options` into an `Option` of a `List` We will use our old friend `foldLeft` to accumulate the result by going through each `Option[TvShow]` on the `List` and returning `Some[List[TvShow]]` only if there are no `Nones` . Quick `foldLeft` recap follows. `List[A].foldLeft(z: B)(f: (B, A) => B): B` Accumulates a value of type **`B`** by applying the function passed as **`f`** to each element of the original list ( **`A`** ) and current accumulator value ( **`B`** ). The shape of the data structure ( **`List`** ) is lost as well as its size and sequence of elements. Only one value of type **`B`** is returned. ![](/images/book/grokking-functional-programming/d6e5e49b-7b0e-44b8-8cc4-d39d82bde095.png) We met `foldLeft` in chapter 4. Back then we suggested that you might also know this functionality as `reduce` . The intuition behind the name is that we fold a list into a single value. What we need to do is start with the accumulator value of `Some(List.empty)` and then fold (or _reduce_ ) the list of `Option[TvShow]` values by _adding_ successfully parsed TV shows to the list or _resigning_ by making the accumulator `None` if there is `None` on the list. ![](/images/book/grokking-functional-programming/d2200da4-d571-4fea-94e6-6091fd4b813b.png) ## We now know how to handle multiple possible errors!

1.   We found out that we can implement the parseShows function using a map and a parseShow .

2.   In parseShow we could therefore focus on parsing just one TV show, and we started with a straightforward approach by returning a TvShow directly from this function.

Step 1 ✔

Recapping higher-order function .

Errors are handled using higher-order functions we learned about in chapter 4.

3.   We found out that when a given rawShow String is invalidly formatted, we get an exception and crash the application.

4.   We remembered that there is an Option type that models a value that may or may not be there.

5.   We started using Option[TvShow] as a return type of parseShow , making it a pure function that doesn’t lie (or throw!)

Step 2 ✔

Using Option to indicate an erro .

Indicating errors by returning immutable values from for comprehensions we learned about in chapter 5.

6.   We were able to divide the functionality of parseShow into three separate small functions: extractName , extractYearStart , and extractYearEnd —all of which return an Option to signal parsing failure or success.

7.   We found out that checked exceptions don’t compose as well as Option , which has the orElse function .

Step 3 ✔

Functional error handling vs. checked exception .

Using the functional approach helps us indicate and handle errors in a much more readable and concise way than checked exceptions.

8.   We then moved on to parsing lists of Strings inside parseShows . The compiler made us decide what to do with rawShow String s that had invalid formatting. First, we used toList and flatten to ignore errors and return a List[TvShow] without signaling that some shows were not parsed—the best-effort error-handling strategy.

9.   We figured out that we can go even further and return an Option[List[TvShow]] from parseShows and use foldLeft to accumulate the result using a different strategy: all-or-nothing.

Step 4 ✔

Handling many errors at onc .

Defining higher-order functions that handle many errors using code that handles just a single error.

We are almost there! Before we meet the last protagonist of the chapter, let’s see what we’ve achieved. At the beginning of the chapter we were tasked with a requirement to parse raw TV shows. This alone took us on quite a journey: Now, it’s time to wrap up the chapter and show you one last trick that will make sure you’ll never miss exceptions again. **Descriptive errors** . Coming up next ... **Using `Either` to indicate descriptive error** . Indicating errors by returning immutable values that contain more information about what failed. ## How to know what failed In the last part we implemented the all-or-nothing error-handling strategy inside the `parseShows` function. Let’s assume this is what the business required from us. Now the function returns an `Option` if at least one of the raw TV shows can’t be parsed.

>

parseShows(List("Chernobyl (2019)", "Breaking Bad (2008-2013)"))  → Some(List(TvShow("Chernobyl", 2019, 2019),
             TvShow("Breaking Bad", 2008, 2013)))   ① 
→ None
parseShows(List("Chernobyl (2019)", "Breaking Bad"))
→ None

① As we can see, everything works correctly! We managed to implement a totally different logic for error handling by changing just a single function! We didn’t have to change the function responsible for parsing one show ( parseShow still returns Option[TvShow] ). This showcases the power of modularity that FP promotes!

Let’s disturb this idyllic view for a bit and look at the usage of the new version of `parseShows` from a more critical perspective. Look at the last two results in the code listing above. We get a `None` as a result—we know that something failed. However, **we don’t know what!** There are multiple functions involved inside `parseShows` and the functions it uses—and each one returns an `Option` . Anything can “fail,” and all we get is `None` . We can’t have any idea why some of the `rawShows` have not been parsed. We could have used a wrong parenthesis, forgotten about years, used a dash in the wrong place, or a multitude of other problems. And all we get is `None` . This approach gets more problematic when we try to use `Options` as error indicators in more complex logic. In huge lists, where many things can go wrong, `Option` is not our best friend anymore.                                                    ![](/images/book/grokking-functional-programming/c8c68461-c3e1-4415-8713-6ca07bc122e3.png) Q Isn’t it worse than exceptions? When an exception is thrown, we know exactly where and why! A We know that exceptions give us more information than `Option` . However, as we already discussed, exception-based code is much less composable, and we need to write much more code whenever we want to conditionally or partially recover from errors. Q So you’ve been rambling about error handling using `Option` s for like 40 pages, and now you tell me it’s bad? A The `Option` type may not be the best choice, but all the things we used with `Option` can be immediately used for other, more descriptive types! It’ll pay off! ## We need to convey error details in the return value If something fails, we want to know why! `Option` is good for handling errors and recovering from errors, but if something fails, all we get is `None` . So we need something that works like `Option` but, additionally, allows us to give and propagate specific information about errors.

Fortunately, Scala and other FP languages have us covered here as well. There is a type that can convey information about a particular error, and it gives us all the functions we learned about when we handled errors using Option . And by all , I mean just that. If you know how to handle errors using Option , you already know how to handle errors using this new type.

It’s called `Either` This new type is called `Either` , or, more specifically, `Either[A, B]` . Just like `Option` , it has two subtypes. ![](/images/book/grokking-functional-programming/696247c3-31ac-4d5a-83ff-3e59b560ae04.png) As you can see, these data types look pretty similar. Particularly, both `Right` and `Some` look identical, and it’s not a coincidence. When dealing with possible error scenarios, these types are used to convey information about a successful case. The main difference is with the second subtype: `None` is just that—a single value. `Left` , however, can hold a `value` , just like `Some` and `Right` ! So in `Either` , we can specify a value that will be present in the result for both successful ( `Right` ) and error ( `Left` ) cases. Let’s see the comparison: The type of value stored if an `Either` is `Left` ( `A` ) can be any type (primitive or product type). We will use `String` in this chapter, but generally a “description of an error" can be a more complex type. ↓
def extractName(show: String): Either[String, String] = {    val bracketOpen = show.indexOf('(')
  if (bracketOpen > 0)
    Right(show.substring(0, bracketOpen).trim)
  else
    Left(s"Can't extract name from $show")
}
def extractName(rawShow: String): Option[String] = {
  val bracketOpen = rawShow.indexOf('(')
  if (bracketOpen > 0)
    Some(rawShow.substring(0, bracketOpen).trim)
  else
    None
}

If you prefix your String with s, you will be able to print values inside this String using the $ prefix.

  

>

extractName("(2022)")
→ Left("Can't extract name from (2022)")

>

extractName("(2019)")
→ None
## Conveying error details using `Either` If you still don’t know why `Either` is such a big deal, the following paragraphs should clarify a lot! We will reiterate what we learned about functional error handling and how it gives us the very helpful skill of indicating descriptive errors. We’ll see how changing the return type of `parseShows` from `Option` to `Either` helps us understand the error a lot quicker—and it does that using almost exactly the same code! Traditionally, any time we introduce a new type or a function, we start with signatures and usages. `Either` won’t be an exception! Before we start coding, let’s compare the `Option` -based signature (which doesn’t give us any hint about error details) with the `Either` -based one (which gives us a description of an error as a `String` ). Excuse the exception pun, but I hope it helps get the point across: using `Either` is the functional alternative to imperative exception-based error handling. Before Returning `Some[TvShow]` (or `None` if something goes wrong) ``` def parseShows(rawShows: List[String]): Option[List[TvShow]] ``` Now Returning `Right[List[TvShow]]` (or `Left[String]` if something goes wrong) ``` def parseShows(rawShows: List[String]): Either[String, List[TvShow]] ``` ![](/images/book/grokking-functional-programming/bca78b35-9351-457e-be13-66dda5fd8660.png) Now, let’s test our intuition and see how this kind of function could be used in the real world. Again, there is no implementation yet, we just do a dry run of the signature to make sure we know what it should return: \* \* This, again, is called test-driven development, or TDD! We first define the test by calling an unimplemented function and asserting its output. We’ll cover TDD in chapter 12! ```erlang parseShows(List("The Wire (2002-2008)", "[2019]")) → Left("Can't extract name from [2019]") parseShows(List("The Wire (-)", "Chernobyl (2019)")) → Left("Can't extract single year from The Wire (-)") parseShows(List("The Wire (2002-2008)", "Chernobyl (2019)")) → Right(List(TvShow("The Wire", 2002, 2008), TvShow("Chernobyl", 2019, 2019))) ``` Note that both `Left("Can't extract name from [2019]")` and `Right(List(TvShow(...))` are **just immutable values of type `Either`** . `Left` is a more helpful value than `None` because it holds a description! ## Refactoring to `Either` We’ll spend the rest of this chapter refactoring `parseShows` and functions it depends on to use `Either` instead of `Option` . I promise that learning `Either` will not be as hard as learning `Option` because both types share many things in common. This means your existing experience with `Option` will come in handy. As we go, please note how a few changes in the code make such a big difference from the client-code perspective. That’s the power of pure functions that get and return immutable values! How can we approach such a big change in the codebase? Let’s go through each step of the refactoring, looking at the big picture of our current solution and seeing how it changes when we introduce `Either` . ![](/images/book/grokking-functional-programming/5ce489ff-9421-4f29-95a5-ef9523875146.png) We have six refactoring steps. Each of the six functions that return an `Option` now will need to be rewritten to return an `Either` . We will approach these refactorings by starting from the smallest `extract` function and finishing with rewriting `parseShow` and `parseShows` . The `Left` value of `Either` can be parametrized with any other type, not just `String` . We will show an example of that in chapter 12. ## Returning an `Either` instead of an `Option` We have six refactoring steps to do before wrapping up this chapter: ① Change the return type of `parseShows to Either[String, List[TvShow]]` . ② Change the return type of `parseShow to Either[String, TvShow]` . ③ Change the return type of `extractName to Either[String, String]` . + ④ Change the return type of `extractYearStart to Either[String, Int]` . \* ⑤ Change the return type of `extractYearEnd to Either[String, Int]` . + ⑥ Change the return type of `extractSingleYear to Either[String, Int]` . + \* We will start from here! + You will do these on your own! **This will give us descriptive errors** —we will know exactly what failed! We can split the workload almost equally between me and you—the reader. The plan is to show you how to refactor `extractYearStart` (number 4 on our list) and then let you refactor the three remaining `extract` functions as an exercise. I hope your existing experience with `Option` —plus seeing how **`extractYearStart`** will have been refactored—will be enough to refactor these three functions on your own. Let’s start. ![](/images/book/grokking-functional-programming/fb52b0c9-3e7c-4afe-95f1-e035efa7313d.png) We start with the signature: our function takes a `String` and returns an `Either[String, Int]` : ``` def extractYearStart(rawShow: String): Either[String, Int] = { ??? } ``` ![](/images/book/grokking-functional-programming/6b96898c-f757-4028-bb21-a594670c4e0a.png) ![](/images/book/grokking-functional-programming/2db15fb9-61e7-48ec-8936-84395807824f.png) To get the start year, we need to find separator characters first:     `"TITLE ( **START** -END)":` `bracketOpen ⬏      ⬑ dash` ``` def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') ??? } ``` ![](/images/book/grokking-functional-programming/bcb8df6d-5e35-4f20-8145-67d8e47e6123.png) We know that `String.substring` can throw an exception, but we want to use `Either` instead. That’s why we need to call `String.substring` only when we know it won’t fail: ``` def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') if (bracketOpen != -1 && dash > bracketOpen + 1) ① Right(rawShow.substring(bracketOpen + 1, dash)) else Left(s"Can't extract start year from $rawShow") } ``` ① Compilation error!     `Either[String, String]` This looks almost identical to the `Option` version, doesn’t it? there are two differences. First is that we wrap the value in `Right` , instead of `Some` . Second is that we return a more descriptive error message wrapped in a `Left` , instead of plain, nondescriptive `None` in the `Option` version. This assures us that if this function returns a `Left` , it will bubble up to the top. We will know what will have failed by looking at it: `"Can't extract start year from Chernobyl [2019]"` . **There is still a compilation error, though: we have an `Either[String, String]` but need an `Either[String, Int]`** . (Remember that the left type in `Either` is the type parameter of `Left—String` in our case—and the right type is the type parameter of `Right` , which should be an `Int` ! ![](/images/book/grokking-functional-programming/9df014ce-356c-416b-9184-ed0c31113cb4.png) Our signature says that we return an `Either[String, Int]` , but our implementation returns an `Either[String, String]` instead. We need to transform the right `String` into an `Int` . ``` def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') val yearStrEither = if (bracketOpen != -1 && dash > bracketOpen + 1) ① Right(rawShow.substring(bracketOpen + 1, dash)) else Left(s"Can't extract start year from $rawShow") yearStrEither.map(yearStr => yearStr.toIntOption) ②③ } ④ ``` ① `Either[String, String]` ② `String` ③ `Option[Int]` ④ Compilation error!     `Either[String, Option[Int]]` `yearStrEither` is a value of type `Either[String, String]` , which means it can be either a `Left[String]` or a `Right[String]` . If it’s a `Left[String]` , then we need to return it, because it is an error, and the `String` contains an error message. If it’s a `Right[String]` , however, we know that this is a substring that should contain the start year. So we want to transform this `String` into an `Int` but only if `yearStrEither` is a `Right[String]` . It turns out that this is a pattern we learned about earlier and already used in the `Option-based` version: we need to use the map! If we map over a `Left` , the result is the same `Left` . If we map over a `Right` , the result is `Right` with the value produced by the function we gave to map! It works exactly like in `Option` , where `Some` gets mapped and `None` doesn’t.

>

val e: Either[String, String] = Right("1985")  e.map(_.toIntOption)
→  Right(Some(1985))

>

val e: Either[String, String] = Left("Error")
e.map(_.toIntOption)
→  Left("Error")
In this case we mapped using `String.toIntOption` again. As you remember, it tries to parse an integer value from a given `String` . If it’s possible, it returns an `Option[Int]` . If it’s not, it returns `None` ! So we are mapping the right `String` of `Either[String, String]` using a function `String => Option[Int]` , and that's why we get an `Either[String, Option[Int]]` back. **The compiler is not happy; it wanted `Either[String, Int]` , not `Either[String, Option[Int]]`** . ![](/images/book/grokking-functional-programming/1ee35c79-87c9-4c77-a66f-5ad3bb7184be.png) Our signature says that we return an `Either[String, Int]` , but our implementation returns an `Either[String, Option[Int]]` instead. We need to transform the internal `Option[Int]` into an `Int` . However, we can’t safely get the `Int` out of an `Option[Int]` because it may be `None` . What we can do is transform the `Option[Int]` into an `Either[String, Int]` by using a new pure function: `toRight` . This way, we will end up with `Either[String, Either[String, Int]]` . ```kotlin def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') val yearStrEither = if (bracketOpen != -1 && dash > bracketOpen + 1) ① Right(rawShow.substring(bracketOpen + 1, dash)) else Left(s"Can't extract start year from $rawShow") yearStrEither.map(yearStr => ② yearStr ②③ .toIntOption ②④ .toRight(s"Can't parse $yearStr") ②⑤ ) ②⑥ } ``` ① `Either[String, String]` ② `Either[String, Either[String, Int]]` ③ `String` ④ `Option[Int]` ⑤ `Either[String, Option[Int]]` ⑥ Compilation error!     `Either[String, Either[String, Int]]` `yearStrEither` is mapped using a function that takes a `String` and returns an `Either[String, Int` . Remember that `map` is concerned only with the `Right` value—it maps only the successful value, not the error value. That’s why the call to `map` changes only the right type, where, instead of the `String` , we get `Either[String, Int]` . This means that the expression creates a value of type `Either[String, Either[String, Int]]` , which looks complicated but is very helfpul, which we'll see in a moment. Inside the `map` function that transforms a `String` , we add the `toRight` function call. **This function converts an `Option` into an `Either` .** If the `Option` is `Some` , it returns the same value inside `Right` . If it’s `None` , it returns the value we’ve provided—in our case a `String—wrapped` inside `Left` .

>

Some(1985).toRight("Can't parse it")  →  Right(1985)

>

None.toRight("Can't parse it")
→  Left("Can't parse it")
**But our code doesn’t compile; we want `Either[String, Int]` , not `Either[String, Either[String, Int]]`** . ![](/images/book/grokking-functional-programming/a3a166b1-9f33-48f8-b03f-4af3947b81d7.png) Our signature says that we return an `Either[String, Int]` , but our implementation returns an `Either[String, Either[String, Int]]` instead. We can flatten it to `Either[String, Int]` ! ```kotlin def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') val yearStrEither = if (bracketOpen != -1 && dash > bracketOpen + 1) ① Right(rawShow.substring(bracketOpen + 1, dash)) else Left(s"Can't extract start year from $rawShow") yearStrEither.map(yearStr => ② yearStr.toIntOption.toRight(s"Can't parse $yearStr") ).flatten ③ } ``` ① `Either[String, String]` ② `Either[String, Either[String, Int]]` ③ `Either[String,Int]` `yearStrEither` is a value of type `Either[String, String]` , which is transformed into an `Either[String, Either[String, Int]]` using a `map` call. Any time we have a nested type like this one, we can flatten it to get rid of one level of nesting. It works exactly like in `List` and `Option` :

>

List(List(1985)).flatten  →  List(1985)

List(List()).flatten
→  List()

>

Some(Some(1985)).flatten
→  Some(1985)

Some(None).flatten
→  None

>

Right(Right(1985)).flatten
→  Right(1985)

Right(Left("Error")).flatten
→  Left("Error")
**Now it compiles!** Notice that the flattening part makes sure that if there is any error, it will be our result. Again, this is an example how `flatten` (and `flatMap` ) propagates the first error ("short-circuiting"). ![](/images/book/grokking-functional-programming/5cc7aa1d-64a4-4ac6-a408-383d401a19a4.png) Have you noticed that we used `map` and `flatten` again? That means we can simplify the whole thing into a `flatMap` call, like in `Option` . If we can use `flatMap` , we can also write it as a for comprehension, which should look very natural to you by now: ``` def extractYearStart(rawShow: String): Either[String, Int] = { val bracketOpen = rawShow.indexOf('(') val dash = rawShow.indexOf('-') for { yearStr <- if (bracketOpen != -1 && dash > bracketOpen + 1) Right(rawShow.substring(bracketOpen + 1, dash)) else Left(s"Can't extract start year from $rawShow") year <- yearStr.toIntOption.toRight(s"Can't parse $yearStr") } yield year } ``` The for comprehension works in the context of `Either` , which is defined by the first generator. It creates a value of `Either[String, String]` and saves the right `String` as `yearStr` (or stops and returns the `Left[String]` if the expression returned it). Then, the second generator uses the value from the first expression, `yearStr` , and returns `Either[String, Int]` . Again, if this is `Left[String]` , it is immediately returned as a result of the whole for comprehension. If it’s `Right[Int]` , then the right value, `Int` , is saved as year, which is yielded as the result of the expression, inside `Either` . **Now we have a working code, which is safe and readable.** Based on the provided `String` , it returns `Either[String, Int]` , which means that it returns a `Right[Int]` if the function can extract a year from the `String` , or a `Left[String]` containing an error description otherwise. Now, let’s test how this function behaves in the real world.

>

extractYearStart("The Wire (2002-2008)")  → Right(2002)

extractYearStart("The Wire (-2008)") 
→ Left("Can't extract start year from The Wire (-2008)")

extractYearStart("The Wire (oops-2008)") 
→ Left("Can't parse oops")

extractYearStart("The Wire (2002-)") 
→ Right(2002)
Note that no matter what `String` we pass, we always get a value back! Some values are the years wrapped inside `Rights` , and some are error messages wrapped inside `Lefts` . But we always get something back! ## Practicing safe functions that return `Either` ![](/images/book/grokking-functional-programming/f2e85480-b7f6-4d6e-966f-f5ca29402648.png) ① Change the return type of `parseShows to Either[String, List[TvShow]]` . $ ② Change the return type of `parseShow to Either[String, TvShow]` . $ ③ Change the return type of `extractName to Either[String, String]` . + ④ Change the return type of `extractYearStart to Either[String, Int]` . \* ⑤ Change the return type of `extractYearEnd to Either[String, Int]` . + ⑥ Change the return type of `extractSingleYear to Either[String, Int]` . + $ We’ll do them afterwards. \* We have just implemented this! + You now need to code these! Now it’s your turn to code something. **Your task is to implement the three missing `extract` functions.** Each of them gets a `rawShow String` and returns an `Either` . Use the REPL to write and test all three functions. Answers 3 ``` def extractName(rawShow: String): Either[String, String] = { val bracketOpen = rawShow.indexOf('(') if (bracketOpen > 0) Right(rawShow.substring(0, bracketOpen).trim) else Left(s"Can't extract name from $rawShow") } ``` We get the index of the bracket. If it’s found, we return `Right` with the name inside. If not, we return `Left` with an error message inside. 5 ``` def extractYearEnd(rawShow: String): Either[String, Int] = { val dash = rawShow.indexOf('-') val bracketClose = rawShow.indexOf(')') for { yearStr <- if (dash != -1 && bracketClose > dash + 1) Right(rawShow.substring(dash + 1, bracketClose)) else Left(s"Can't extract end year from $rawShow") year <- yearStr.toIntOption.toRight(s"Can't parse $yearStr") ① } yield year } ``` ① This line is repeated in three functions. Maybe we should extract it into its own small function? We get the index of the dash and closing bracket. If they are found and the closing bracket is further in the string than the dash, we can safely call the `substring` function and pass the string to the next phase, which parses the integer. 6 ```kotlin def extractSingleYear(rawShow: String): Either[String, Int] = { val dash = rawShow.indexOf('-') val bracketOpen = rawShow.indexOf('(') val bracketClose = rawShow.indexOf(')') for { yearStr <- if (dash == -1 && bracketOpen != -1 && bracketClose > bracketOpen + 1) Right(rawShow.substring(bracketOpen + 1, bracketClose)) else Left(s"Can't extract single year from $rawShow") year <- yearStr.toIntOption.toRight(s"Can't parse $yearStr") } yield year } ``` We get the index of the dash and both opening and closing brackets. If there is no dash but brackets are found and the closing bracket is further in the `String` than the opening one, we can safely call the `substring` function and pass the `String` to the next phase. ## What we learned about `Option` works with `Either` ![](/images/book/grokking-functional-programming/85d894eb-d6ec-4bd9-a31f-52654b2a5f40.png) Together we’ve completed four out of six refactoring steps. I hope that you’ve already noticed that we have almost exactly the same code using `Either` as we had when we used `Option` . The only difference is that instead of `None` , we use a `Left` value with a `String` that describes the problem. Now, it’s time to use our new four functions to parse a single raw show.

2a

We want to change the return type to Either[String, TvShow] .

``` def parseShow(rawShow: String): Option[TvShow] = { ① for { name <- extractName(rawShow) yearStart <- extractYearStart(rawShow).orElse(extractSingleYear(rawShow)) yearEnd <- extractYearEnd(rawShow).orElse(extractSingleYear(rawShow)) } yield TvShow(name, yearStart, yearEnd) } ``` ① Compilation error!     `Either[String, TvShow]` `parseShow` returns an `Option` , but `extractName` and other extract functions already return `Either` ! That means that our for comprehension expression is already of type `Either[String, TvShow]` ! But our signature still says that we return an `Option[TvShow]` . **This is a compilation error: our implementation returns `Either[String, TvShow]` , but the signature promises `Option[TvShow]` !** To fix this compilation error, we need to adjust the signature to the implementation, and we are done! Yes, that means that `Either-version` of `parseShow` is identical to the `Option` version.

2b

We need to change the return type in the signature to Either[String, TvShow] . No more changes are needed, because Either also has orElse .

``` def parseShow(rawShow: String): Either[String, TvShow] = { for { name <- extractName(rawShow) yearStart <- extractYearStart(rawShow).orElse(extractSingleYear(rawShow)) yearEnd <- extractYearEnd(rawShow).orElse(extractSingleYear(rawShow)) } yield TvShow(name, yearStart, yearEnd) } ``` That’s it! When we refactored `extractName` and other `extract` functions to use `Either` , we did all the heavy lifting! Thus, only the signature needed to be changed in `parseShow` . It also turned out that `Either` has an `orElse` function that works similarly to the `Option` one. ![](/images/book/grokking-functional-programming/ab69b526-5ff5-4d9d-ab27-cfb7b24f0a9d.png)
parseShow("The Wire (-)")  → Left("Can't extract single year from The Wire (-)")
parseShow("The Wire (oops)") 
→ Left("Can't parse oops")
parseShow("(2002-2008)") 
→ Left("Can't extract name from (2002-2008)")
parseShow("The Wire (2002-2008)") 
→ Right(TvShow("The Wire", 2002, 2008))

Once we use Option / Either , everything else gets “tainted" and bubbles up to client code! That’s the way to make sure an error is explicitly handled.

## Coffee break: Error handling using `Either` ![](/images/book/grokking-functional-programming/88b0d64e-9f60-451a-98f7-a43eefe9450e.png) We now know that everything we learned about implementing error indication and handling using `Option` is useful when we use `Either` . This final exercise of the chapter will make sure that you understand functional error handling. **Your task is to refactor the** `parseShows` . ① Change the return type of `parseShows to Either[String, List[TvShow]]` . \* ② Change the return type of `parseShow to Either[String, TvShow]` . ③ Change the return type of `extractName to Either[String, String]` . ④ Change the return type of `extractYearStart to Either[String, Int]` . ⑤ Change the return type of `extractYearEnd to Either[String, Int]` . ⑥ Change the return type of `extractSingleYear to Either[String, Int]` . \* Your final quest! Here’s a reminder of how `parseShows` should work. It implements the all-or-nothing error-handling logic, which means that if at least one raw TV show can’t be parsed, the error is returned (inside a `Left` !). Try to implement this function from scratch before going forward. This is a harder version of this exercise, but you have all the knowledge to implement it. Use your time, and try to solve it. If you do, the rest of the book will be a lot easier! ```erlang parseShows(List("The Wire (2002-2008)", "[2019]")) → Left("Can't extract name from [2019]") parseShows(List("The Wire (-)", "Chernobyl (2019)")) → Left("Can't extract single year from The Wire (-)") parseShows(List("The Wire (2002-2008)", "Chernobyl (2019)")) → Right(List(TvShow("The Wire", 2002, 2008), TvShow("Chernobyl", 2019, 2019))) ``` Hint If you spent a substantial amount of time trying to implement **`parseShows`** from scratch, and you can’t figure it out, here’s the `Option` -based version.

parseShows

addOrResign

def parseShows(rawShows: List[String]): Option[List[TvShow]] = {    val initialResult: Option[List[TvShow]] = Some(List.empty)
  rawShows
    .map(parseShow)
    .foldLeft(initialResult)(addOrResign)
}
def addOrResign(
  parsedShows: Option[List[TvShow]],
  newParsedShow: Option[TvShow]
): Option[List[TvShow]] = {
  for {
    shows      <- parsedShows
    parsedShow <- newParsedShow
  } yield shows.appended(parsedShow)
}

parseShows uses the addOrResign helper function. Both use Option as a type that conveys information about an error. You need to make them work with Either instead

⤷

## Coffee break explained: Error handling using `Either` ![](/images/book/grokking-functional-programming/88b0d64e-9f60-451a-98f7-a43eefe9450e.png) The final exercise of a chapter should be challenging, but I hope you’ve enjoyed this ride! Let’s do it together step by step:

1a

We want to change the return type to Either[String, List[TvShow]] .

![](/images/book/grokking-functional-programming/69f53c2c-99d9-4da7-929d-c61f25145a97.png)

1b

Let’s change the signature to Either[String, List[TvShow]] and see what the compiler has to say.

![](/images/book/grokking-functional-programming/f357faea-7bad-4855-91c2-e79dc5b7f79b.png)

1c

Let’s change the initialResult and addOrResign to use Either instead of the Option to make the compiler happy.

![](/images/book/grokking-functional-programming/119a2278-d714-4b6e-a745-7b1748076600.png) ## Working with `Option` / `Either`

Before we finally wrap this chapter up, let’s talk about the essence of functional error handling. Errors are encoded as immutable values. To handle errors, we write pure functions, which internally use map , flatten , flatMap , orElse , and toRight / toOption . All these functions are defined in both Option and Either types, which look and behave similarly. Let’s summarize how we’ve worked with both of them in this chapter.

It’s important to understand all these functions before moving on. Use the REPL, and follow the code to make sure you really grokked them all.

Working with Option

Working with Either

>

val year: Option[Int] = Some(996)  val noYear: Option[Int] = None

>

val year: Either[String, Int] = Right(996)
val noYear: Either[String, Int] = Left("no year")

map

map

  
year.map(_ * 2)
→  Some(1992)
noYear.map(_ * 2)
→  None
  
year.map(_ * 2)
→  Right(1992)
noYear.map(_ * 2)
→  Left("no year")

flatten

flatten

  
Some(year).flatten
→  Some(996)
Some(noYear).flatten
→  None
  
Right(year).flatten
→  Right(996)
Right(noYear).flatten
→  Left("no year")

flatMap

flatMap

  
year.flatMap(y => Some(y * 2))
→  Some(1992)
noYear.flatMap(y => Some(y * 2))
→  None
year.flatMap(y => None)
→  None
noYear.flatMap(y => None)
→  None
  
year.flatMap(y => Right(y * 2))
→  Right(1992)
noYear.flatMap(y => Right(y * 2))
→  Left("no year")
year.flatMap(y => Left("can't progress"))
→  Left("can't progress")
noYear.flatMap(y => Left("can't progress"))
→  Left("no year")

orElse

orElse

  
year.orElse(Some(2020))
→  Some(996)
noYear.orElse(Some(2020))
→  Some(2020)
year.orElse(None)
→  Some(996)
noYear.orElse(None)
→  None
  
year.orElse(Right(2020))
→  Right(996)
noYear.orElse(Right(2020))
→  Right(2020)
year.orElse(Left("can't recover"))
→  Right(996)
noYear.orElse(Left("can't recover"))
→  Left("can't recover")

toRight

toOption

  
year.toRight("no year given")
→  Right(996)
noYear.toRight("no year given")
→  Left("no year given")
  
year.toOption
→  Some(996)
noYear.toOption
→  None
## Summary In this chapter you’ve learned a lot about functional error handling. Additionally, you validated all the knowledge you gained in previous chapters. You are now a proficient user of immutable values and pure functions. CODE: `CH06_*` Explore this chapter’s source code by looking at `ch06_*` files in the book’s repository.

Handle errors without null s and exceptions

We encountered the problematic substring calls that failed for some Strings . We learned that in FP all errors are just values, and we can use them instead of null s and exceptions.

Step 1

Recapping higher-order function .

Errors are handled using higher-order functions we learned about in chapter 4.

Make sure all corner cases are handled

We learned that using checked exceptions for error handling is not as composable as using Option or Either . When a function returns an exception, we needed to first catch it and then decide how to handle the error and recover from it. In Option and Either , we were able to use the orElse function that takes two immutable values that may be representing errors and returns one of them. This approach scales very well.

Step 2

Using Option to indicate an erro .

Indicating errors by returning immutable values from for comprehensions we learned about in chapter 5.

Indicate errors in the function signature

Our pure functions indicate when they may fail by exposing this information through their signatures. If a function returns an Option or Either , it’s saying that for some arguments the result may not be generated.

Step 3

Functional error handling vs. checked exception .

Using the functional approach helps us indicate and handle errors in a much more readable and concise way than checked exceptions.

Compose bigger functionalities from smaller functions in the presence of errors

We learned that we can divide the requirement into very small ones and implement a function for each of them with a custom error message that will be propagated if it’s encountered. We built bigger functions (that handle lists) by composing them from these small functions. The compiler made us handle all possible errors along the way. Finally, we implemented the all-or-nothing error-handling strategy by using our old friend— foldLeft .

Step 4

Handling many errors at onc .

Defining higher-order functions that handle many errors using code that handles just a single error.

  

Return user-friendly and descriptive errors

On top of that, we learned that when we used Either we were able to provide very detailed error messages as Left[String] .

Step 5

Using Either to indicate descriptive error .

Indicating errors by returning immutable values that contain more information about what failed.