concept parseshow in category functional programming

appears as: parseShows, parseShow
Grokking Functional Programming

This is an excerpt from Manning's book Grokking Functional Programming.

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 case class:

Let’s try to make the parseShow function more trustworthy by using the powers of the Option type. Our parseShow function will return Option-typed value to let the user know whether the parsing succeeded or not:

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. If you still wonder what’s wrong with throwing a checked exception*, which is also visible in the signature, please keep on reading. There are more reasons not to use exceptions than this and we will cover all of them soon. But before we do, let’s focus on our new parseShow.

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:

* As a reminder, if your function throws a checked exception, it needs to indicate that in the signature by adding throws clause. We will cover this soon and we will compare this approach with the functional one.

 

In the last part we implemented the all-or-nothing 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))) #A
 
parseShows(List(“Chernobyl [2019]”, “Breaking Bad (2008-2013)”))
→ None
 
parseShows(List(“Chernobyl (2019)”, “Breaking Bad”))
→ None

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 now 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 wrong parenthesis, forgotten about years, used dash in a wrong place or 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 a more complex logic. In huge lists where many things can go wrong, Option is not our best friend anymore.