In this chapter you will learn
-
how to model your immutable data to minimize errors
-
how to model your requirements as immutable data
-
how to find problems in requirements using the compiler
-
how to make sure your logic is always executed on valid data
“ Designing something just powerful enough is an art. ”
—Barbara Liskov
Modeling data to minimize programmers’ mistakes
In this chapter we will change the way we model data in our applications. We will use more types to minimize potential programmer mistakes. We will learn techniques that enhance the maintainability of our codebases. We will also make implementations smaller and less complicated! Too good to be true? Let’s see this in action using an example.
We focus a lot on maintainability in this book. As a reminder, we say that a given codebase is maintainable if it’s easy to change without introducing bugs.
Music artist catalogue
As always, we’ll start with a potential real-world application. We will implement a music artist catalogue that will help us find artists by genres, their locations, or years they were active. There will be lots of corner cases to handle, and the main focus will be on data modeling. We will be modeling artists. Each artist will have a name, a main genre, and an origin. Seems easy, right? We just need to define a product type.
case class Artist(name: String, genre: String, origin: String)
What problems do you see with this definition of an artist .
There are many problems with this approach, but they all can be summarized like this: this data model makes the implementation based on it harder and more error-prone. The compiler allows many invalid instances like Artist("", "", "") or Artist("Metallica", "U.S", "Heavy Metal") , and it forces programmers to handle each of them in the code. (Do you see what the problem is with the latter value?) These kinds of mistakes are easy to make; they are not checked by the compiler, and they are pretty hard to debug in many cases. The funny thing is that they all originate from using primitive types , such as String s and Int s, to model real-world, more complicated business entities and relations. | |
This is just a simplified version of the Artist definition we’ll work with in this chapter. We will define the complete set of requirements soon.
So far we’ve used String s or Int s to describe the data we used in our pure functions. In this chapter we can finally try to be better at data modeling. There are multiple problems we will list, explain, and propose a functional solution to. You will learn how to model data to make the implementation a lot easier, starting with modeling an artist using only what we’ve learned earlier (and primitive types). Then, we will discuss and analyze each possible mistake a programmer could make using this naive model. Solutions will come next. Let’s go!
Some experience from the object-oriented world will come in handy as well!
Well-modeled data can’t lie
So far in this book we’ve focused on implementing requirements using pure functions with signatures that tell readers what’s going on inside. Pure functions don’t lie, which makes reading code a breeze; readers don’t need to go through each line of code to understand what it’s doing. They just look at the signature and move on.
In this chapter we will show how we can apply exactly the same techniques to model our data! In FP, we try to make our jobs easier by modeling data in a way that prevents representation of some invalid combinations! That’s the superpower behind functional design. | |
Enough introductions, let’s code! We are faced with writing new software—a new function—that fulfills the following requirements.
Requirements: Music artist catalogue
-
The function should be able to search through a list of music artists.
-
Each search should support a different combination of conditions: by genre, by origin (location), and by period in which they were active.
-
Each music artist has a name, genre, origin, year their career started, and a year they stopped performing (if they are not still active).
Note that of the three requirements above, the first two are behavioral requirements , while the last one is a data requirement . So far we’ve been focusing on behaviors (functions), and we modeled data requirements as simple types: String s, Int s, and Boolean s. We will start with this approach and quickly pivot to using safer functional programming techniques for both behaviors and data.
Good design makes an easy implementation
There will be five big general problems, and we will address each of them by introducing a functional programming technique that solves this particular problem and makes the model far more bulletproof . Being bulletproof means that only valid combinations of data from the business domain are possible in the implementation. This approach cuts a lot of impossible corner cases at the compilation level, so programmers don’t need to worry about handling them. In the end our Artist definition will not only be bulletproof but also smaller, more readable, and far easier to work with. Interested?
THIS IS BIG!
In FP, we model data so that only valid business combinations are possible.
Quick exercise Write your version of the Artist product type, which implements the third requirement above. Show your best design! | Answers in discussion. |
Designing using what we know so far (which is primitive types)
I hope you’ve finished the quick exercise and written your own version of the Artist data model on a piece of paper so that you can compare and see how good your initial intuition was. We will start implementing the music artist catalogue data model using only the tools and techniques we have learned in previous chapters. The requirement for our data states the following:
Notice that we use the terms data modeling and data design interchangeably in this book. They mean the same thing (i.e., how we transfer business entities into data structures).
Each music artist has a name, genre, origin (location), year their career started, and a year they stopped performing (if they are not still active).
This looks like something we could model using a product type.
case class Artist(
name: String, ①
genre: String, ①
origin: String, ①
yearsActiveStart: Int, ②
isActive: Boolean, ②
yearsActiveEnd: Int ②
)
① Name, genre, and origin location are modeled as raw Strings .
② Artists always have a year they started being active. We model that as a raw Int . If an artist is not active (isActive=false), yearsActiveEnd represents the year they stopped being active. However, some may be still active (isActive=true) and then yearActiveEnd should be 0.
Implementing behaviors that use the data
Now that we have modeled the data using a product type, we can implement the behavior—as a pure function—that uses this data. Let’s start with the most important thing in FP: the function’s signature.
The function should be able to search through a list of music artists.
Each search should support different combination of conditions: by genre, by origin, and by period in which they were active.
def searchArtists(
artists: List[Artist], ①
genres: List[String], ②
locations: List[String], ②
searchByActiveYears: Boolean, ③
activeAfter: Int, ③
activeBefore: Int ③
): List[Artist] ④
① The incoming list of artists that contains all the artists we want to search through
② These two Lists represent two search conditions, and they work in a similar way. If a List is empty, we don't want to search using this condition. If it’s not empty, we require that the resulting artists have the genres/locations specified in the list.
③ These three parameters together represent one search condition. If the Boolean flag is false , we don’t trigger this condition. If it’s true , we want to return only artists that were active within the activeAfter-activeBefore period (given in years as Int s).
④ The resulting list of artists that contains all the artists that satisfy given conditions
Using data modeled as primitive types
We used primitive types to model the data requirements. As you probably expect, this is far from ideal. However, it’s still a very common practice, and many software architectures are built this way. You are probably aware of some limitations of this approach, but let’s try to list them all.
We’ll create a list of artists and search through them to get a feeling of how our primitive type–based model behaves in the real world. (Additionally, you will be tasked with implementing this raw version of searchArtists very soon, so it’s a good idea to pay attention here.)
Note that we don’t say that this design is universally bad. It may have its benefits, like better performance. However, this book focuses on readability and maintainability in codebases. We argue that in this aspect primitive type–based modeling is not a good choice.
Here’s a small list of all artists we are going to use in this chapter. The list has one active artist (as of date of publication) and two inactive ones.
> | val artists = List( Artist("Metallica", "Heavy Metal", "U.S.", 1981, true, 0),
Artist("Led Zeppelin", "Hard Rock", "England", 1968, false, 1980),
Artist("Bee Gees", "Pop", "England", 1958, false, 2003)
) |
This is how we’d like to use our `searchArtists` function:
We still don’t have an implementation of `searchArtists,` and you’ve probably already got accustomed to this approach. Remember: Usage comes first, and implementation comes last.
```php
searchArtists(artists, List("Pop"), List("England"), true, 1950, 2022) ①
→ List(Artist("Bee Gees", "Pop", "England", 1958, false, 2003))
searchArtists(artists, List.empty, List("England"), true, 1950, 2022) ②
→ List(
Artist("Led Zeppelin", "Hard Rock", "England", 1968, false, 1980),
Artist("Bee Gees", "Pop", "England", 1958, false, 2003)
)
searchArtists(artists, List.empty, List.empty, true, 1981, 2003) ③
→ List(
Artist("Metallica", "Heavy Metal", "U.S.", 1981, true, 0),
Artist("Bee Gees", "Pop", "England", 1958, false, 2003)
)
searchArtists(artists, List.empty, List("U.S."), false, 0, 0) ④
→ List(Artist("Metallica", "Heavy Metal", "U.S.", 1981, true, 0))
searchArtists(artists, List.empty, List.empty, false, 2019, 2022) ⑤
→ List(
Artist("Metallica", "Heavy Metal", "U.S.", 1981, true, 0),
Artist("Led Zeppelin", "Hard Rock", "England", 1968, false, 1980),
Artist("Bee Gees", "Pop", "England", 1958, false, 2003)
)
```
① Pop artists from England active between 1950–2022.
② Artists from England active between 1950–2022. An empty list means we don’t care about genre.
③ Artists active between 1981–2003. Empty lists mean we don’t care about genre and location.
④ Artists from the United States with all other conditions disabled.
⑤ All conditions disabled. Note that years we provided don’t matter because the flag is `false` .
## Coffee break: The pain of primitive types 
There are several serious problems with the approach we have just presented. It looks and works correctly, but it’s very error-prone, and we will show all the places where programmers like us can make a mistake. That’s what this exercise is for. You will have a go and try to implement the `searchArtists` function yourself. Can you get it right on your first try? Second? We will learn how to model data so that implementing behaviors such as `searchArtists` is a breeze. Let’s feel the pain first, though!
**Your task is to implement** `searchArtists` **as a pure function that has the signature we’ve discussed above** .
```
def searchArtists(
artists: List[Artist], ①
genres: List[String], ①
locations: List[String], ①
searchByActiveYears: Boolean, ③
activeAfter: Int, ③
activeBefore: Int ③
): List[Artist] ④
```
① The incoming list of artists that contains all the artists we want to search through
② These two `Lists` represent two search conditions, and they work in a similar way. If a `List` is empty, we don't want to search using this condition. If it’s not empty, we require that the resulting artists have the genres/locations specified in the list.
③ These three parameters together represent one search condition. If the Boolean flag is `false` , we don’t trigger this condition. If it’s `true` , we want to return only artists that were active within the `activeAfter-activeBefore` period (given in years as `Int` s).
④ The resulting list of artists that contains all the artists that satisfy given conditions
Here are the use cases you should test against to make sure you have covered all bases:
Search for pop artists from England active between 1950 and 2022: searchArtists(artists, List("Pop"), List("England"), true, 1950, 2022) Search for artists from England active between 1950 and 2022: searchArtists(artists, List.empty, List("England"), true, 1950, 2022)Search for artists active between 1950 and 1979: searchArtists(artists, List.empty, List.empty, true, 1950, 1979) Search for artists active between 1981 and 1984: searchArtists(artists, List.empty, List.empty, true, 1981, 1984) Search for heavy-metal artists active between 2019 and 2022: searchArtists(artists, List("Heavy Metal"), List.empty, true, 2019, 2022)Search for artists from the U.S. active between 1950 and 1959: searchArtists(artists, List.empty, List("U.S."), true, 1950, 1959)Search for artists without any conditions: searchArtists(artists, List.empty, List.empty, false, 2019, 2022) ① ① It’s not a mistake, but including years here feels misleading, doesn’t it?
| List of artists to test with Use these three artists in tests: - Metallica, Heavy Metal, U.S., 1981–now, - Led Zeppelin, Hard Rock, England, 1968–1980 - Bee Gees, Pop, England, 1958–2003 |
## Coffee break explained: The pain of primitive types 
I hope you’ve had some fun implementing the `searchArtists` function. As always has been the case in this book, there are different possible correct solutions. Make sure all the test cases listed in the task description are satisfied! Here’s one possible (and annotated) solution:
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist => ①
(genres.isEmpty || genres.contains(artist.genre)) && ②
(locations.isEmpty || locations.contains(artist.origin)) &&
(!searchByActiveYears || (
(artist.isActive || artist.yearsActiveEnd >= activeAfter) &&
(artist.yearsActiveStart <= activeBefore)))
)
```
① We need to use the `filter` higher-order function that takes a function, which is executed against each artist and returns `true` if it should be included in the output list.
② If `genres` is not empty, we check whether the artist has a genre from the list. The same story is true with `locations` .
If the `searchByActiveYears` is `true` , we check whether the artist was active in the specified period. If an artist is still active, we only check the start year. Otherwise, we check both start and end years.
Did you enjoy all the nasty **nested ifs** ? Let’s see how they work:
```erlang
searchArtists(artists, List("Pop"), List("England"), true, 1950, 2022)
→ List(Artist("Bee Gees", "Pop", "England", 1958, false, 2003))
searchArtists(artists, List.empty, List("England"), true, 1950, 2022)
→ List(Artist("Led Zeppelin", ...), Artist("Bee Gees", ...))
searchArtists(artists, List.empty, List.empty, true, 1950, 1979)
→ List(Artist("Led Zeppelin", ...), Artist("Bee Gees", ...))
searchArtists(artists, List.empty, List.empty, true, 1981, 2003)
→ List(Artist("Metallica", ...), Artist("Bee Gees", ...))
searchArtists(artists, List("Heavy Metal"), List.empty, true, 2019, 2022)
→ List(Artist("Metallica", "Heavy Metal", "U.S.", 1981, true, 0))
searchArtists(artists, List.empty, List("U.S."), true, 1950, 1959)
→ List()
searchArtists(artists, List.empty, List.empty, false, 2019, 2022)
→ List(Artist("Metallica", ...), Artist("Led Zeppelin", ...),
Artist("Bee Gees", ...))
```
They work fine! The main outcome of this exercise, however, is this nagging feeling that it shouldn’t be that hard. We should be able to implement these kinds of features without thinking much about the internals, right? What if I told you that **the way we modeled the `Artist` is the reason why implementing `searchArtists` was so difficult** ? Now that you’ve felt the pain of implementing this function, let’s see how the functional approach to modeling data could have made the job easier.
## Problems with the primitive type approach to modeling
We now know that implementing behaviors (like the `searchArtists` function) based on primitive type data models is possible but error-prone. Let’s cut to the chase and list three of the most important problems that we’ll address and present a functional solution to in this chapter.
**Primitive type–based model** Our current version that works, but is error-prone:
```
case class Artist(name: String, genre: String, origin: String,
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int)
```
Problem 1
**Programmers need to be careful about the order of parameters** .
Answer this without looking at the product type definition: is the code below a valid representation of an artist?
```
Artist("Metallica", "U.S.", "Heavy Metal", 1981, true, 0)
→ compiles! ①
```
① (unfortunately)
It surely is for the compiler because it compiles fine! **However, it’s not a valid value** because the parameters of `genre` and `origin` have been misplaced. There is no geographical `Heavy Metal` location, although I’m pretty sure some people would love it!
Problem 2
**Programmers need to know the additional meaning of parameter combinations** .
What about this? Is this a valid artist?
```
Artist("Metallica", "Heavy Metal", "U.S.", 1981, false, 2022)
→ compiles! ①
```
① (but it’s not valid)
We agreed that to model an active artist, we should set `isActive` to `true` . If `isActive` is `true` , then the `yearsActiveEnd` parameter doesn’t matter and should be set to 0. These parameters are interconnected, which means that we can represent lots of different combinations, but many of them will not be valid in terms of our domain.
Problem 3
**Programmers need to ensure that some parameters have a finite set of values** .
Is this a valid representation of an artist?
```
Artist("Metallica", "Master of Puppets", "U.S.", 1981, true, 0)
→ compiles! ①
```
① (again, compiler hasn’t helped)
We put the name of the album as a genre, and the compiler gladly accepted it. But we know that there is a finite number of possible genres to choose from. If we are making a music-based software, we can safely narrow down the genres we support. `String` doesn’t help us there at all. It can hold many more values than there are music genres.
## Using primitive types makes our jobs harder!
But there’s more ! We also have similar problems with our behavior (the `searchArtists` pure function)! When you look closer, you can see that it also uses primitive types as parameters. Similar problems arise.
**Primitive type–based model** Our current error-prone version of function parameters:
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int): List[Artist]
```
Problem 4
**Programmers need to come up with, understand, and convey additional meanings to primitive types** .
What does genres: `List[String]` mean in the `searchArtists` signature? If it’s empty, it means we shouldn’t search using the genre criteria. If it’s not empty, it means that this is a required criterium: returned artists should have at least one of the genres on the list. See how much explanation is needed? It’s an explanation that is not conveyed by just writing genres: `List[String]` because it’s just a list of `String` s that happens to be named genres.
Problem 5
**Programmers need to remember that some parameters only make sense when used together** .
The `activeAfter` and `activeBefore` parameters can only be used together. They both implement the requirement of “filtering artists that were active in the given period.” Additionally, they are only applicable when `searchByActiveYears` is `true` . So as you can see, there is a lot of semantic bundling of different parameters, which, again, is not directly explainable by looking at the function signatures and product type definitions.
We’ve just seen how using primitive types in models and functions caused a lot of silly mistakes. We were able to represent combinations that are not valid regarding the business domain, but they were OK for the compiler. So, on top of real valid combinations that represent the logic our users want, we need to additionally understand and take care of all the invalid combinations that are representable only because we modeled our data using primitives . More work for us! We can, and will, do better. We will address all five problems by reusing some techniques we already know and learning two very important new ones. Additionally, we will build on things we learned in the previous chapters where we used the compiler to find and report many of these mistakes. The remaining parts of this chapter tackle all five problems, one problem at a time. | |
## Newtypes protect against misplaced parameters
Let’s start with the simplest new technique, which is used widely in functional programming. Let’s tackle the first problem.
**Current model** Our current version that works, but is error-prone:
```
case class Artist(name: String, genre: String, origin: String,
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int)
```
Problem 1 
**Programmers need to be careful about the order of parameters** .
The `String` parameters (e.g., genre and origin) can be misplaced.
Let’s look at the above definition again. We see three `String` parameters, which means all of them can be misplaced, and the compiler won’t complain. So all of the following invalid combinations are possible (i.e., compilable):
> | Artist("Metallica", "U.S.", "Heavy Metal", 1981, true, 0) Artist("U.S.", "Metallica", "Heavy Metal", 1981, true, 0)
Artist("U.S.", "Heavy Metal", "Metallica", 1981, true, 0) |
Introducing newtypes There is a very straightforward technique that can protect us from these kinds of mistakes, making our lives a lot easier in the process. It’s called newtype , also known as a zero-cost wrapper . Instead of using primitive types like String , we wrap it in a named type. | If you want to define the Location type in the REPL, make sure to put it inside an object definition . then use |
| ⤴ |
Now we can use `Location` as a separate type ( `String` will not do! `):`
```
val us: Location = Location("U.S.") ①
val wontCompile: Location = "U.S."
→ compilation error!
```
① You could achieve exactly the same result by creating a `case class Location(name: String)` . However, newtypes are zero-cost wrappers, which means they are just `String` s in the runtime.
The compiler understands a `String` is not a `Location` . Let’s use it!
## Using newtypes in data models
We can now use the `Location` newtype we have just created to update our `Artist` model.
**Updated model** We are now using the Location newtype.
```
case class Artist(name: String, genre: String, origin: Location,
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int)
```
That means that now the compiler has our back when we mistakenly try to misplace the parameters.
> | Artist("Metallica", Location("U.S."), "Heavy Metal", 1981, true, 0) → compilation error!
Artist(Location("U.S."), "Metallica", "Heavy Metal", 1981, true, 0)
→ compilation error!
Artist(Location("U.S."), "Heavy Metal", "Metallica", 1981, true, 0)
→ compilation error! | |
The newtype pattern is ubiquitous in functional programming. You can encode it in many languages, including Haskell, Rust, and Kotlin. In some of them, however, it involves a bit of boilerplate code.
Pure win! There is only one place that Location fits in, but in the runtime it will still behave like a bare String ! We can’t get it wrong. This is a very small and subtle change, but it provides us with an additional layer of safety without any performance costs . | |
In terms of usage, there is not much difference. Instead of `artist.origin` , which was a bare `String` , we now need to use `artist.origin.name` inside the Boolean expression in `searchArtists` .
Note that we focus on data modeling in this part of the chapter. That’s why the `searchArtists` signature will still use primitive types. We will fix it when we get to behavior modeling.
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist =>
(genres.isEmpty || genres.contains(artist.genre)) &&
(locations.isEmpty || locations.contains(artist.origin.name)) && ①
(!searchByActiveYears || (
(artist.isActive || artist.yearsActiveEnd >= activeAfter) &&
(artist.yearsActiveStart <= activeBefore)))
)
```
① The only change needed after introducing the `Location` newtype is here. We need to extract the raw `String` for comparison.
Problem 1 ✔ Solved by the newtype.
**Programmers need to be careful about the order of parameters** .
The `String` parameters (e.g., genre and origin) can be misplaced.
## Practicing newtypes 
It’s time to use newtypes in the rest of our `Artist` definition.
**Exercise** Replace primitive types with more newtypes.
```
case class Artist(name: String, genre: String, origin: Location,
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int)
```
Let’s leave the `name` as a `String` for now. There shouldn’t be any more `String` s (besides the `name` ) in the definition after you finish this exercise. Note also that there are also two `Int` s, which we can misplace. Please use newtypes there as well. **Your task is to introduce three newtypes and use them in** **`Artist`** **and** **`searchArtists`** **.** These are: `Genre` ( `String` ), `YearsActiveStart` ( `Int` ), and `YearsActiveEnd` ( `Int` ).
Answers
> | object model { ① opaque type ②
object Genre {
def apply(value: String): Genre = value
extension(a: Genre) def name: String = a
}
opaque type YearsActiveStart = Int
object YearsActiveStart {
def apply(value: Int): YearsActiveStart = value ③
extension(a: YearsActiveStart) def value: Int = a
}
opaque type YearsActiveEnd = Int
object YearsActiveEnd {
def apply(value: Int): YearsActiveEnd = value
extension(a: YearsActiveEnd) def value: Int = a ④
}
case class Artist(name: String, genre: Genre, origin: Location,
yearsActiveStart: YearsActiveStart,
isActive: Boolean, yearsActiveEnd: YearsActiveEnd)
}
import model._ ⑤
artists.filter(artist => ⑥
(genres.isEmpty || genres.contains(artist.genre.name)) &&
(locations.isEmpty || locations.contains(artist.origin.name)) &&
(!searchByActiveYears || (
(artist.isActive || artist.yearsActiveEnd.value >= activeAfter) &&
(artist.yearsActiveStart.value <= activeBefore)))
)① We will bundle all types from our model inside the model module . ② We create three newtypes that “wrap” primitive values in the compile time (remember that in runtime they are still behaving like primitive values). We start with Genre , which internally is just a String , but the compiler won’t allow us to use String s as Genre s. ③ We “add” two functions to all our newtypes. The apply function allows us to create a newtype value (like YearsActiveStart ) from a primitive value ( Int ). ④ The value extension function allows us to extract primitive values from the newtype wrapper values (see below). ⑤ Functions that want to use our data model will need to import everything from the model module . ⑥ We need to change the implementation of the searchArtists function and “unwrap” newtype-based values at the call site inside (using extension functions we defined on each of them). |
There is nothing magical about the newtype. It’s a tool that allows the compiler to help us. It also improves the readability!
## Making sure only valid data combinations are possible
There is an even better technique we can use to model `genre` and active years, so let’s revert your changes and leave only the `Location` newtype. The second technique is a little bit more complex than newtypes but as ubiquitous. Let’s look at the definition again.
**Current model** Our current model uses the Location newtype.
```
case class Artist(name: String, genre: String, origin: Location, ①
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int)
```
① Note that so far we only introduced a `Location` newtype. A genre and active years can also be modeled as newtypes (which you’ve shown in the previous exercise), but we are going to use a more fitting technique now.
We see three parameters that are used to describe the active years requirement: `yearsActiveStart` , `isActive` , and `yearsActiveEnd` . Note how `isActive` and `yearsActiveEnd` are interconnected. Whenever you see more than one parameter describing a single logical business entity inside your data class, you can be sure that it will cause headaches.
```
Artist("Metallica", "Heavy Metal", Location("U.S."),
1981, true, 2022) ①
Artist("Led Zeppelin", "Hard Rock", Location("England"),
1968, true, 1980) ②
```
① 2022 doesn’t matter here because `isActive = true` . It can be misleading!
② 1980 is the real year that Led Zeppelin stopped being active, but again, it doesn’t matter because `isActive = true` . The programmer may not see it right away!
Modeling complex entities
Our problem is that we have three parameters that, together, make up a single business entity. We want to model a period of time, which may be open-ended; it always has a start, but it might not have an end. We will show you the best functional way to approach such a problem in a bit, but let’s first start with modeling the `end` part. Do we already know any type that can be used to represent something that may or may not be there?
Using `Option` to describe our data
We’ve used the `Option` type as a return type of our pure functions (behaviors). But this simple type is so versatile that it can do even more! It models a potentially missing value, so it fits well in the active years requirement. See? We learned one thing a few chapters earlier, and now we can use it in more scenarios—and the fact is that functional programmers really use the `Option` type all the time. That’s why we introduced it so early in the book.
## Modeling possibility of absence in your data
Any time you see more than one value representing a single logical business entity, make sure to stop and think how to model it better. As an example, we now have two parameters that together make up a single entity. This is a very common pattern in programming in general: a Boolean flag plus a parameter that is only applicable if the Boolean flag is true . I am sure you recognize this pattern. We will show you two ways of approaching this pattern using functional programming techniques: the Option type and algebraic data types . First up is the Option type. | |
**Current model** A version that uses primitive types to represent active years.
```
case class Artist(name: String, genre: String, origin: Location,
yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int) ①
```
① These two parameters represent a single logical entity: the time an artist stopped being active. They are interconnected logically, but our code doesn’t ensure this because each of these two parameters can be set to any value, independently.

Updated model A version that uses the `Option` type instead.
```
case class Artist(name: String, genre: String, origin: Location,
yearsActiveStart: Int, yearsActiveEnd: Option[Int]) ①
```
① We replaced two parameters that always needed to be written and interpreted together with a single parameter that models the potential absence of a value (in this case the value is an end year in a period of time).

Let’s see our problematic example to make sure it really helped our case.
```
Artist("Metallica", "Heavy Metal", Location("U.S."),
1981, None) ①
Artist("Led Zeppelin", "Hard Rock", Location("England"),
1968, Some(1980)) ②
```
① `None` means there is no end year because the artist is still active. We can’t put any year as an end year!
② 1980 is the real year Led Zeppelin stopped being active, so to define it we need to pass `Some` , which means the artist has an end year and, therefore, is not active anymore.
Now, it’s not possible to make any mistake because we have only one parameter that models the whole logical entity of the _end year_ . The `Option` type models a value that may not be there. It’s exactly what we needed here. The end year may not be there only if the artist is still active!
## Changes in the model force changes in the logic
We changed our `Artist` data model substantially (there is one parameter less!), so it should be obvious that we need to change the behavior—the logic implemented as a function—that uses this data model. Let’s see how the new definition of the `Artist` model is going to be used by the `searchArtists` function, which implements the main requirement.
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist =>
(genres.isEmpty || genres.contains(artist.genre)) &&
(locations.isEmpty || locations.contains(artist.origin.name)) &&
(!searchByActiveYears || (
(artist.isActive || artist.yearsActiveEnd >= activeAfter) &&
(artist.yearsActiveStart <= activeBefore)))
)
```

We got a compilation error! As we can see, using an `Option` is not that straightforward as using primitive types. We know how to compare `String` s and `Int` s with each other and how `Boolean` s can be used as conditions. As we’ve shown in the `searchArtists` case, once we get the conditions right it’s very rewarding. But we’ve also shown that modeling data using only primitive types is not the best way to create maintainable software. That’s why we’ve introduced—and plan to introduce even more—techniques that make our models more robust. The cost of these refactorings is that we also need to make amendments in our logic. They are not straightforward, but—surprise, surprise they make the logic more robust as well! Let’s see!
In our case, we now have an `Option` value inside our model. This value represents an end year of an artist’s active period. It may or may not be there, depending on whether a given artist stopped performing. That makes sense, but now how do we check whether an artist was active in the specified `activeAfter` and `activeBefore` period?
```
case class Artist(name: String, genre: String, origin: Location,
yearsActiveStart: Int, yearsActiveEnd: Option[Int]) ①
```
① We need to compare these two values inside an artist with the specified `activeAfter` and `activeBefore` parameters that are part of the search logic. Note that we can’t just compare an `Int` with an `Option[Int]` because these are different types!
## Using data modeled as `Option` s in your logic
Again, the problem we face now is that we need to somehow implement the logic of checking whether an artist was active between given `activeAfter` and `activeBefore` years. Specifically, how can we check that `artist.yearsActiveEnd >= activeAfter` , knowing that `artist.yearsActiveEnd` is an `Option[Int]` ?
```
artist.yearsActiveEnd: Option[Int]
activeAfter: Int
```
You may be tempted to use the `yearsActiveEnd == Some(year)` condition or the `yearsActiveEnd == None` condition, and while it’s possible, it’s not a preferred approach in FP.
How can we compare these two values? So far, we’ve had an `Int` - `Int` comparison, which was triggered only when `isActive` wasn’t `true` :
```
(artist.isActive || artist.yearsActiveEnd >= activeAfter)
```
Now we got rid of `isActive` and modeled `yearsActiveEnd` as an `Option` . What should we do? It turns out that `Option` **has even more** hidden **goodies than we dared to imagine** . And by goodies I obviously mean higher-order functions: functions that take functions as arguments (or return functions)! We will meet more of them soon! First, let’s recap what we know.
THIS IS BIG!
In FP, each type has many higher-order functions.
### Higher-order functions for `Option`
> | val year: Option[Int] = Some(996) val noYear: Option[Int] = None |
| map | flatMap | filter |
| | year.map(_ * 2) → Some(1992)
noYear.map(_ * 2)
→ None
| | 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.filter(_ < 2020)
→ Some(996)
noYear.filter(_ < 2020)
→ None
year.filter(_ > 2020)
→ None
noYear.filter(_ > 2020)
→ None |
And some new ones: forall exists !
The first one is called `forall` . We can write our condition for the active years requirement as follows:
```
artist.yearsActiveEnd.forall(_ >= activeAfter) ①
```
① Remember that `_ >= activeAfter` is a shorthand for: `activeEnd =>` `activeEnd >= activeAfter`
`forall` returns `true` if the element inside the given `Option` (if the `Option` is `Some` ) satisfies the condition passed as an anonymous function or if there is no element inside the `Option` (i.e., it is `None` ).
It’s a function that takes one parameter and returns a Boolean.
## Higher-order functions for the win!
`forall` is a higher-order function defined on `Option` . It takes one function as a parameter, just like `map` , `flatMap` , and `filter` .
`Option[A].forall(f: A => Boolean): Boolean`
Applies the function passed as **`f`** to the element held by this `Option` . Returns `true` if this `Option` is empty ( `None` ) or the given function **`f`** returns `true` when applied to this `Option` ’s value.
Intuitively, we say, “If this represents a value, check if it satisfies the given condition, and if there is no value, ignore the condition.”
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist =>
(genres.isEmpty || genres.contains(artist.genre)) &&
(locations.isEmpty || locations.contains(artist.origin.name)) &&
(!searchByActiveYears || (
(artist.yearsActiveEnd.forall(_ >= activeAfter)) &&
(artist.yearsActiveStart <= activeBefore)))
)
```
We removed one parameter from the model and removed one additional condition inside our logic. Now, our model is more robust, and our logic is a little bit simpler to comprehend.
Learning about many higher-order functions is a functional programmer’s bread and butter. In this book we just scratch the surface of what’s at your disposal. What I want you to take away, however, is how useful they are and how you can apply them for many different requirements. Remember: The signature, documentation, and examples are your allies! Let’s see some usage example of `forall` , compared with `filter` and a totally new one: `exists` . **Can you learn about** **`exists`** **just by looking at its signature and examples** .
> | val year: Option[Int] = Some(996) val noYear: Option[Int] = None |
| forall | exists | filter |
| | year.forall(_ < 2020) → true
noYear.forall(_ < 2020)
→ true
year.forall(_ > 2020)
→ false
noYear.forall(_ > 2020)
→ true | | year.exists(_ < 2020)
→ true
noYear.exists(_ < 2020)
→ false
year.exists(_ > 2020)
→ false
noYear.exists(_ > 2020)
→ false | | year.filter(_ < 2020)
→ Some(996)
noYear.filter(_ < 2020)
→ None
year.filter(_ > 2020)
→ None
noYear.filter(_ > 2020)
→ None |
## There is probably a higher-order function for that!
The lesson from all of this is that whenever you work with an immutable FP type like Option , List , or Either and you have a problem implementing logic around it, you should remember that there probably is a higher-order function for your use case. (And if there’s not, what keeps you from implementing it? You will probably need it again!) | |
We have just met `forall` and, hopefully, `exists` . It turns out that these functions are not only available for `Option` s but can also be found in `Either` , `List` , and many more types! Again, the power of FP is that you learn one thing for one type, and you can almost immediately apply it in many different scenarios. `forall` is just one example, but if you are curious about more examples, look no further. Remember `contains` , which we used on `Strings` and `Lists` ? Do you think it’s available in `Option` as well? If it was, what do you think its behavior would be?
THIS IS BIG!
There is a higher-order function available for all the common use cases!
Yes, `Option` does have the `contains` function defined. You will soon find out how to use it. Note that `contains` is not really a higher-order function because it doesn’t take a function nor return a function. However, it is an example of a function defined on more than one immutable type, which is also known universally by all developers. This example is intended as an intuition for you if you still struggle with the idea of usefulness of higher-order functions.

Q If there is a higher-order function for all common cases, doesn’t it mean that there are lots of them?
A There are definitely plenty of them, yes. However, note that usually they can be used in many situations, and when you learn about a new higher-order function using one type, you already know how it works on lots of other types. For example, you know how `forall` works for `Option` . That means you already know how `forall` works on `Either` , `List` , and even the types you haven’t learned about yet! The same thing applies to `exists` , `map` , `flatMap` , `flatten` , `filter` , `foldLeft` , `orElse` , and others. You learn once and use it everywhere. As a bonus, this knowledge doesn’t expire, and it carries over to other functional languages! How cool is that?
## Coffee break: `forall` / `exists` / `contains` 
It’s time to take a small break from the `Artist` data model and practice your intuition when it comes to implementing behaviors using three functions— `forall` , `exists` , and `contains` —on two types: `Option` and `List` . I know that we’ve only talked about `Option.forall` and `List.contains` . That means that you will need to, as a part of this exercise, figure out `List.forall` , `Option.exists` , `List.exists` , and `Option.contains` on your own!
User search functionality
Assume there is an unchangeable data model already at your disposal:
> | case class User(name: String, city: Option[String], favoriteArtists: List[String]) |
The user of our system has a name, potentially a city, and has a list of favorite artists (provided as `String` s to make this exercise more self-contained—I hope you will let it slide and not turn your nose up at the fact that we still use primitive types instead of newtypes here).
Here’s a list of users we will use in this exercise:
> | val users = List( User("Alice", Some("Melbourne"), List("Bee Gees")),
User("Bob", Some("Lagos"), List("Bee Gees")),
User("Eve", Some("Tokyo"), List.empty),
User("Mallory", None, List("Metallica", "Bee Gees")),
User("Trent", Some("Buenos Aires"), List("Led Zeppelin"))
) |
**Your task is to implement six functions that take a list of users and return a list of users that satisfy a given condition** . Each function implements one condition to make things a little bit easier:
- `f1` : users that haven’t specified their city or live in Melbourne
- `f2` : users that live in Lagos
- `f3` : users that like Bee Gees
- `f4` : users that live in cities that start with the letter T
- `f5` : users that only like artists that have a name longer than eight characters (or no favorite artists at all)
- `f6` : users that like some artists whose names start with an M
Hint: All the implementations should be very concise, so if you feel like a condition needs a lot of implementation, take a break, go for a walk, and come back to think again. Remember that we want to show differences between three functions defined on two types.
Make sure to test your solution before looking at the next page!
## Coffee break explained: `forall` / `exists` / `contains` 
I hope you’ve had some fun with this one, and you were able to figure at least some of the six functions on your own! Here are the six solutions that are the standard way of implementing such requirements in FP.
- `f1` : users that haven’t specified their city or live in Melbourne
> | def f1(users: List[User]): List[User] = users.filter(_.city.forall(_ == "Melbourne"))
f1(users).map(_.name)
→ List("Alice", "Mallory") ①① We are mapping the return lists with a function that leaves only the name so that the output is cleaner. |
1
Option has a `forall` function that takes a condition. If the `Option` is `None` or if the value inside `Some` satisfies the condition, `true` is returned.
- `f2` : users that live in Lagos
> | def f2(users: List[User]): List[User] = users.filter(_.city.contains("Lagos"))
f2(users).map(_.name)
→ List("Bob") |
2
`Option` has a `contains` function that takes a value of internal `Option` ’s type. In this case it’s a `String` . `contains` returns `true` if this `Option` ’s `String` equals the given one.
- `f3` : users that like Bee Gees
> | def f3(users: List[User]): List[User] = users.filter(_.favoriteArtists.contains("Bee Gees"))
f3(users).map(_.name)
→ List("Alice", "Bob", "Mallory") |
3
`List` has a `contains` function as well! It takes a value of internal `List` ’s type ( `String` ) and returns `true` if this `list` contains the given `String` .
- `f4` : users that live in cities that start with the letter T
> | def f4(users: List[User]): List[User] = users.filter(_.city.exists(_.startsWith("T")))
f4(users).map(_.name)
→ List("Eve") |
4
`Option` has an `exists` function. It takes a function that is a condition. It returns `true` if this `Option` is `Some` and its value satisfies the given condition.
- `f5` : users that only like artists that have a name longer than eight characters (or no favorite artists at all)
> | def f5(users: List[User]): List[User] = users.filter(_.favoriteArtists.forall(_.length > 8))
f5(users).map(_.name)
→ List("Eve", "Trent") |
5
`List` has a `forall` function . It takes a function that is a condition. It returns `true` if this `List` is empty or when all its values satisfy the given condition.
- `f6` : users that like some artists whose names start with an M
> | def f6(users: List[User]): List[User] = users.filter(_.favoriteArtists.exists(_.startsWith("M")))
f6(users).map(_.name)
→ List("Mallory")) |
6
`List` has the `exists` function. It takes a function that is a condition. It returns `true` if this `List` contains at least one element that satisfies the given condition.
## Coupling a concept inside a single product type
Did we solve our problem with `Option` and its overpowered ally `forall` ?
Problem 2 ✔ Can be solved by the `Option` type but only in some cases
**Programmers need to know the additional meaning of parameter combinations** .
A `Boolean flag` and an `Int` parameter (e.g., `isActive` and `activeYearsEnd` ) are interconnected.
We solved it but not entirely. There is one more detail related to this problem that we haven’t addressed so far. Notice how we are talking about _parameter combinations_ . Both `yearsActiveStart` and `yearsActiveEnd` represent a single concept: the period of time an artist was or still is active. Whenever you come to this kind of conclusion, it’s a great indicator that you need to create **yet another product type** .
```
case class PeriodInYears(start: Int, end: Option[Int])
```
See? Now both parameters are coupled together in a single entity that represents a period of time in years. The end is still represented as an `Option` that conveys that it’s possible this value is absent ( `None` ), which in turn makes such an instance of `Period` open-ended. Now, we can use this newly defined `Period` inside our `Artist` definition.
**Current model** A version that uses yet another product type to define the active years.
```
case class Artist(name: String, genre: String, origin: Location, yearsActive: PeriodInYears)
```
Isn’t it better? The definition is getting more and more robust, while becoming smaller and easier to comprehend. What’s not to like about it? Now, let’s see how it is going to be used. Look how descriptive this is and how we lowered the risk of making a programmer’s mistake:

We are going in the right direction! But let’s not rest on our laurels!
Problem 2 ✔ Solved by the product type with a primitive type and an `Option` .
**Programmers need to know the additional meaning of parameter combinations** .
Several parameters (e.g., a `Boolean` flag and two `Ints` ) represent one business entity.
## Modeling finite possibilities
I hope you’ve been enjoying the techniques we’ve introduced so far. They are simple but very useful and universally acclaimed by functional programmers. The next technique is the main part of this chapter and the reason many people prefer functional domain design over other approaches. Let’s have a look at the next problem.
Problem 3 Solved by the product type with a primitive type and an `Option` .
**Programmers need to ensure that some parameters have a finite set of values** .
Some entities in the domain have a finite set of possible values (e.g., music `genre` ).
Here are some manifestations of the problem:
```rust
- Artist("Metallica", "Heavy Meta", Location("U.S."), ①
PeriodInYears(1981, None))
- Artist("Led Zeppelin", "", Location("England"), ②
PeriodInYears(1968, None))
- Artist("Pop","Bee Gees", Location("England""), ③
PeriodInYears(1958, Some(2003))). ③
```
① “Heavy Meta" is not a possible value, but it compiles!
② `""` is not a possible value, but it compiles!
③ “Bee Gees” is not a possible value, but it compiles! (Recap: This one could be solved by a newtype definition we did as an exercise.)
All the above are accepted by the compiler without any issues. And who could blame the compiler? It’s our fault that we modeled the `Artist` in a way that these instances are possible. The good news is that we can solve this problem using one of the most powerful tools in functional programming: **a type that can only take a finite set of values** . In FP that’s a job for a **sum type** . In Scala, it’s encoded as an **`enum`** :
We will explain the name of the sum type very soon. Let’s first use it in practice!
> | enum MusicGenre { case HeavyMetal
case Pop
case HardRock
} |
We defined four types here: `MusicGenre` and its three possible values— `HeavyMetal` , `Pop` , and `HardRock` .
We have just defined a sum type called `MusicGenre` . Before we use it inside our `Artist` definition, let’s use it in a REPL session.
> | import MusicGenre._ val genre: MusicGenre = Pop
→ Pop
val x: MusicGenre = HeavyMeta
→ compilation error!
val y: MusicGenre = "HeavyMeta"
→ compilation error! |

A sum type allows us to delegate even more work to the compiler.
## Using sum types
The sum type makes sure that its value is always legal; it comes from a set defined by us, up front, and unchangeable in the runtime. This is checked and assured by one of our most trusted allies: the compiler. There is no way our application will compile with a wrong value of `MusicGenre` : we can’t use a `String` (so, again, it can’t be misplaced), and we can’t misspell the genre. Hence, we get even broader protection than we did with a newtype.

Q Isn’t it just a plain `enum` ?
A The example we’ve shown looks and serves a similar purpose as `enum` . However, `enum` in Scala is much more powerful than in Java. The sum type is not just a wrapper around a value, it’s more than that. Sum types together with product types can model much more complex concepts, which we’ll see very soon.
Our `Artist` definition has become a lot more polished now:
```
case class Artist(name: String, genre: MusicGenre,
origin: Location, yearsActive: PeriodInYears)
```
Again, remember that we’ve used a lot of product types in this book, and a more in-depth explanation of both product types and sum types is just around the corner.
Just by looking at the definition, we can see what’s going on and what’s necessary. Remember that so far we’ve been just defining data models using types: newtypes, **product types,** and **sum types** . Here’s how this new definition can be used to define real values of artists:
```php
val artists = List(
Artist("Metallica", HeavyMetal, Location("U.S."), PeriodInYears(1981, None)), ①
Artist("Led Zeppelin", HardRock, Location("England"), PeriodInYears(1968, Some(1980))), ①
Artist("Bee Gees", pop, Location("England"), PeriodInYears(1958, Some(2003))) ①
)
def searchArtists(artists: List[Artist], genres: List[MusicGenre], locations: List[String], ②
searchByActiveYears: Boolean, activeAfter: Int, activeBefore: Int): List[Artist]
```
① Look,no quotes needed! Music genres are not `String` s anymore!
② Only a small signature change is needed in the `searchArtists` function. We need to pass a `List` of `MusicGenre` values, not `String` s. The implementation doesn’t need to change.
Look’s good, right? Plus, notice how it’s getting harder and harder to make a mistake. These techniques ensure that our code is both safe and very readable. All these techniques we’ve learned about, when used together, make up very maintainable code. We are giving the compiler a lot more information now, and it’s using it to help us!
Problem 3 ✔ Solved by the sum type
**Programmers need to ensure that some parameters have a finite set of values** .
Some entities in the domain have a finite set of possible values (e.g., music `genre` ).
## Even better modeling with sum types
Our `MusicGenre` type looks better than `String` , but you are probably still not convinced. Why are we glorifying this idea so much? Again, it looks like an `enum` with better type safety but still an `enum` !
What if I told you that we can use sum types—these _glorified_ enums—to improve our `Artist` model even more? Specifically, we can use them to enhance the active years model. We will improve the readability (and maintainability) of the model by making it even more specific than it is right now. That’s the place where we leave the plain old enums analogy far behind. Here’s our current model.
**Current model** A version that uses a sum type, a newtype, and a product type.
```
case class Artist(name: String, genre: MusicGenre, origin: Location, yearsActive: PeriodInYears)
```
What do we want to improve, you may ask? Looking at this type, there are no real issues we could pinpoint, or are there? Let’s focus on the `PeriodInYears` type that represents the active years requirement:
```
case class PeriodInYears(start: Int, end: Option[Int])
```
We wanted to model a period of time, in years, when a given artist was active. There are two options: the artist may still be active, and then the period is open-ended ( `end = None` ), or the artist is no longer active, and then we have a fixed period of time ( `end = Some(endYear)` ).
Did you notice what we just wrote? There are **two options** . They are exclusive—they can’t be used together for the same `Artist` —and they are the only possible values. That’s exactly the same case we had when we modeled finite possibilities. We need to **use a sum type again** !
enum YearsActive { case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int)
} | |
See? We defined two possible values for our `YearsActive` type: `StillActive` and `ActiveBetween` . They explain—in business terms—what they mean. Note how we use product types as possible values and compare to what we did in `MusicGenre` when we used singletons:
THIS IS BIG!
Sum type + product type combo gives us modeling superpowers.
```
enum MusicGenre {
case HeavyMetal
case Pop
case HardRock
}
```
`ActiveBetween` is a product type that bundles two values together. `MusicGenre` didn’t have such cases.
## Using the sum type + product type combo
Notice how we made sure to encode even more business context into the type itself. Now we don’t have to guess or possess any insider knowledge to know what this means. Compare this to the old version to really appreciate how such small changes make such a big difference from the readability aspect. (Did I mention that programmers read the code far more often than they write it? Let’s give them less guesswork and more love!)
**Before** Using a product type + `Option`
```css
case class PeriodInYears(start: Int, end: Option[Int]) ⤵
Artist("Metallica", HeavyMetal, Location("U.S."), PeriodInYears(1981, None))
Artist("Led Zeppelin", HardRock, Location("England"), PeriodInYears(1968, Some(1980)))
```
After Using a sum type + product types
```
enum YearsActive {
case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int) ⤵
}
Artist("Metallica", HeavyMetal, Location("U.S."), StillActive(since = 1981))
Artist("Led Zeppelin", HardRock, Location("England"), ActiveBetween(1968, 1980))
```
Naming is always hard. We could also use `ActiveSince` instead of `StillActive` . Additionally, we can always explicitly repeat the name of the parameter for readability.
Here’s what our model looks like after modeling `genre` and `yearsActive` using sum + product types and `origin` using a newtype:
```typescript
enum MusicGenre {
case HeavyMetal
case Pop
case HardRock
}
opaque type Location = String
object Location {
def apply(value: String): Location = value
extension(a: Location) def name: String = a
}
enum YearsActive {
case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int)
}
case class Artist(name: String, genre: MusicGenre,
origin: Location, yearsActive: YearsActive) ①
```
① Note that we can use only very specific values to create artists, and many constraints are ensured by our old friend: the compiler.
**It’s a very bulletproof model** —it’s both readable and maintainable.
In FP there are some more advanced techniques that are out of the scope of this book, such as type-level programming and dependent types, that allow us to model even more complicated constraints, but the ideas of newtypes, product types, and sum types are still the foundation and main tool in the FP programmer toolbox.
## Product types + sum types = algebraic data types (ADTs)
You may be surprised to know that you’ve just learned one of the most influential and useful concepts in the functional domain design: algebraic data types . In Scala, case class and enum are used together to implement this concept, which is also available in many other functional languages. What are they and what’s algebraic about them? Let’s learn by recapping what we’ve done so far in the data modeling department. | |
First, earlier in this book we introduced the product type, but in this chapter we started to use it more intently. At its core, it bundles together other types, which, together, can be treated as one type with a name. So any time you have a requirement where two business concepts together make up a bigger business concept, you will want to use the product type, just like we did with `PeriodInYears` :
```
case class PeriodInYears(start: Int, end: Option[Int])
```

Secondly, we learned that we can implement a finite set of possible values using a sum type with singleton objects:
```
enum MusicGenre {
case HeavyMetal
case Pop
case HardRock
}
```

Moreover, we learned that there are sum types that have product types as cases with each child having a different set of fields:
```
enum YearsActive {
case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int)
}
```

**So what’s algebraic about them?** When you look at `MusicGenre` or `YearsActive` , you can see that they model something that may only be one of many things at once: the first thing, the second thing, or the third thing, and so on. All these possible options together form a **sum type** . On the other hand, when you look at a `PeriodInYears` or other product types we’ve used, you can see that they model an opposite idea: something that **is** one or more things **at once** : the first thing, the second thing, and the third thing at once . So it’s a _product_ of smaller things—hence, a **product type** \* name. We will use algebraic data types (ADTs) a lot!
\* In set theory, which is related to programming and type theory, types can be treated as sets of values. Many names in FP come from the math background.
## Using ADT-based models in behaviors (functions)
Now, we know two out of five of our modeling problems were solved using an ADT. The last new thing we are going to learn in this chapter is how to use ADT values in our pure functions. Let’s go back to our running example. We want to search for artists, but the `Artist` model changed, and `yearsActive` is now an ADT, so we can’t directly compare it to `activeAfter` and `activeBefore` like we did with primitive values. We also can’t use `Option.forall` anymore because we got rid of the `Option` and modeled the potential absence of a value in a better business-related context.
Problem 2 ✔ Solved by ADTs
**Programmers need to know the additional meaning of parameter combinations** .
Problem 3 ✔ Solved by ADTs
**Programmers need to ensure that some parameters have a finite set of values** .
> | def searchArtists(artists: List[Artist], genres: List[MusicGenre], locations: List[Location], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist =>
(genres.isEmpty || genres.contains(artist.genre)) &&
(locations.isEmpty || locations.contains(artist.origin)) &&
(!searchByActiveYears || ???) ①
)① How can we check whether artist.yearsActive was between activeAfter and activeBefore ? |
Remember how we approached such problems before? Whenever you have more complicated logic that misses some part of a functionality, you can just extract a function that has a well-defined signature and a descriptive name. Then, you can focus on implementing the smaller function. This clears your head from the unnecessary burden and helps you get the job done quicker. What we need here is a function that returns `true` if an artist was active in a given period of time.
> | def wasArtistActive( artist: Artist, yearStart: Int, yearEnd: Int
): Boolean =
??? ① ① Remember that ??? is part of the Scala language. It compiles but throws an exception in the runtime. It helps with designing functions and leaving some implementation for later. In our case, the missing part is something new we want to introduce. |
Before we show you the new technique that deals with ADTs, we can call this new function from `searchArtists` and leave it for now:
```
(!searchByActiveYears ||
wasArtistActive(artist, activeAfter, activeBefore))
```
It’s about time we learn how to _destructure_ ADTs.
## Destructuring ADTs using pattern matching
In the pure `wasArtistActive` function we need to make a decision based on an artist that has `yearsActive` . `YearsActive` is an ADT with two cases: `StillActive` and `ActiveBetween` . Depending on whether `artist.yearsActive` is `StillActive` or `ActiveBetween` , we have different values to work with (the former has just one `Int` named `since` , and the latter has two `Ints` named `start` and `end` ). It all proves that we need (and want) to have a slightly different logic for each case.

```
enum YearsActive {
case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int)
}
```
And this is exactly what we are going to do. **Enter pattern matching** .
❶ | We start with the match keyword; we match on artist.yearsActive, which is a value of YearsActive: |
```
def wasArtistActive(artist: Artist, yearStart: Int, yearEnd: Int): Boolean =
artist.yearsActive match
???
```
❷ | The compiler requires us to handle all cases. YearsActive has two cases (because it’s a sum type with two cases): |
```
def wasArtistActive(artist: Artist, yearStart: Int, yearEnd: Int): Boolean =
artist.yearsActive match {
case StillActive(since) => since <= yearEnd ①②
case ActiveBetween(start, end) => start <= yearEnd && end >= yearStart ③
}
```
① If it’s `StillActive` , destructure it into an `Int` named since.
② Then return since `<= yearEnd` .
③ If `yearsActive` is `ActiveBetween` , destructure it into two `Int` s: `start` and `end` . Then, return the value calculated by the expression to the right of `=>` .
The pattern matching expression destructures a concrete value of a sum type into one of its product type cases, extracts internal values, and calculates the result using the expression provided to the right of the => operator. This becomes the result of the whole pattern matching expression. We know, and the compiler knows too, that YearsActive has two possible values. So any time we want to destructure a YearsActive value, the compiler makes sure we destructure fully (i.e., we don’t miss any case). That’s a huge help. Any time we add a new case to our sum type (new case to an enum ), the compiler will pinpoint each place that doesn’t handle this new case. We will see it in action very soon when we’ll add a new requirement to our artist search engine. Stay tuned. | |
## Duplication and DRY

Q What about the duplication in this pattern match:
```
artist.yearsActive match {
case StillActive(since) =>
since <= yearEnd
case ActiveBetween(start, end) =>
start <= yearEnd && end >= yearStart
}
```
Shouldn’t we try to create an abstraction to remove the duplication of `since/start <= yearEnd` ?
A In this book we embrace code maintainability and readability. That means that we accept duplication if it helps to understand the underlying decision process better. When we destructured the `YearsActive` value, we showed the reader that there are two cases, and they slightly differ. We are directly showing that if an artist is still active, we just care about the end of the search period. There is nothing to mentally decode here.
Compare our current solution with the first version we wrote:
```
def searchArtists(artists: List[Artist], genres: List[String],
locations: List[String], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int
): List[Artist] =
artists.filter(artist =>
(genres.isEmpty || genres.contains(artist.genre)) &&
(locations.isEmpty || locations.contains(artist.origin)) &&
(!searchByActiveYears || (
(artist.isActive || artist.yearsActiveEnd >= activeAfter) &&
(artist.yearsActiveStart <= activeBefore)))
)
```
How easy would it be to implement a new requirement that allows us to search by the length of activity period? Or if the artist could have more than one active period?
Sure enough, it doesn’t have any duplication. How easy was it to read it? Do you remember how hard it was to write it and get it right? When we model data using ADTs and use pattern matching in our functions, we are dividing our workload into small steps and can focus on each of them separately. Later on, the reader can follow our thought process. This makes the code a lot more readable. I am not arguing for duplication here; I am arguing for code maintainability. **Sometimes we don’t need to worry about the DRY principle,** \* especially when the two duplicated code snippets are independent at their core, and only share a similar structure, usually by accident. It’s better to leave them be, duplicated, each evolving in its own direction.
\* We mentioned DRY (don’t repeat yourself) in the first part of the book. As a recap, it is a well-known principle in software development, which aims at reducing the duplication of code by creating abstractions that enhance code sharing between two or more entities. As with other software principles, we should not treat it dogmatically.
## Practicing pattern matching 
Pattern matching , just like ADTs, is universally used in functional programming. That’s why it’s important to train your muscle memory. **Your task is to implement a function that gets an artist and the current year and returns the number of years this artist was active** .
**Current model** A version that uses a newtype and two ADTs
```
case class Artist(name: String, genre: MusicGenre, origin: Location, yearsActive: YearsActive)
enum YearsActive {
case StillActive(since: Int)
case ActiveBetween(start: Int, end: Int)
}
```
Remember that `YearsActive` has two options. That means that your pattern matching expression needs to consider both of them.
Before peeking, make sure your function passes the following tests:
> | def activeLength(artist: Artist, currentYear: Int): Int = ??? // TODO activeLength(
Artist("Metallica", HeavyMetal, Location("U.S."), StillActive(1981)), ①
2022
)
→ 41
activeLength(
Artist("Led Zeppelin", HardRock, Location("England"),
ActiveBetween(1968, 1980)), ②
2022
)
→ 12
activeLength(
Artist("Bee Gees", Pop, Location("England"),
ActiveBetween(1958, 2003)), ③
2022)
→ 45① Metallica have been active for 41 years, as of 2022! ② Led Zeppelin were active for 12 years. ③ Bee Gees were active for 45 years! |
**Bonus questions:** Why do we need to pass the current year? Why can’t we just get the current year inside the function?
Answers
The answer to the coding question can be found on the right. The bonus questions have deeper answers. The short answer is that if we don’t pass a year as an argument, the function is no longer pure! Getting the current year is a side-effectful action, which we’ll address in chapter 8.
```
def activeLength(artist: Artist, currentYear: Int): Int =
artist.yearsActive match {
case StillActive(since) => currentYear - since
case ActiveBetween(start, end) => end - start
}
```
## Newtypes, ADTs, and pattern matching in the wild 

Q This book is about functional programming, but it feels like newtypes, ADTs, and pattern matching are very Scala-specific. Are they?
A They are not Scala-specific! As we mentioned in the first chapter, Scala is used here only as a teaching tool. Newtypes, ADTs, and pattern matching are all available in other languages, so it’s beneficial that you understand these concepts and practice them. Plus, as a side effect, you’re learning some Scala!
Moreover, these tools are being added to traditionally imperative languages. Pattern matching, for example, has been added to both Java and Python.
To prove this point, let’s go through some examples of newtypes, ADTs, and pattern matching in other languages: **F#** and **Haskell** .
F# (You don't have to understand this code, it's just to show F# you these tools are reusable in many functional languages.)
```haskell
type MusicGenre = HeavyMetal | Pop | HardRock ①
type YearsActive = StillActive of int | ActiveBetween of int * int ②
type Location = struct ③
val value:string
new(value) = { value = value }
end
type Artist = {Name:string; Genre:MusicGenre; ④
Origin:Location; Active: YearsActive}
let metallica = {Name="Metallica"; Genre=HeavyMetal; ⑤
Origin=Location "U.S."; Active=StillActive 1981}
let totalActive = match metallica.Active with ⑥
| StillActive since -> 2022 - since
| ActiveBetween (activeStart, activeEnd) -> activeEnd - activeStart
```
① `MusicGenre` is a sum type.
② `YearsActive` is a sum type that consists of two product types.
③ We can use a `struct` with one field (with some performance cost) instead of newtype.
④ `Artist` is a product type.
⑤ This is an example of how we can create a value of an `Artist` in F#.
⑥ Since `YearsActive` is a sum type, we can destructure it using a pattern matching expression.
Haskell
```haskell
data MusicGenre = HeavyMetal | Pop | HardRock
data YearsActive = StillActive Int | ActiveBetween Int Int
newtype Location = Location { value :: String }
data Artist = Artist { name :: String, genre :: MusicGenre,
origin :: Location, yearsActive :: YearsActive }
let metallica = Artist "Metallica" HeavyMetal
(Location "U.S.") (StillActive 1981)
let totalActive = case yearsActive metallica of
StillActive since -> 2022 - since
ActiveBetween start end -> end - start
```
A very similar code can be written in Haskell. As you can see, these concepts really are universal! Once you learn them in Scala, you will be able to apply this knowledge quickly in other languages. Learning the syntax will be the only obstacle.
## What about inheritance?

Q Isn’t the ADT concept just glorified inheritance? We can define two or three subtypes of an interface or an abstract class and achieve a similar result, right? Or is there more to it?
A The similarity between ADTs and the inheritance concept from OOP may be striking, but it quickly becomes clear that they are very different. There are two major and defining differences between these concepts:
1. ADTs don’t contain behaviors, while in OOP data (mutable fields) and behaviors (methods that mutate those fields) are bundled together in an object. In FP, data and behaviors are separate entities. Data is modeled using immutable values (like ADTs or raw values), and behaviors are independent pure functions.
2. When we define a sum type, we must provide all possible values of this type, and the compiler always checks whether we handle all cases in functions that destructure this sum type. \*
\* And remember that we have pattern matching at our disposal that allows us to easily destructure ADTs, which is not possible to do with imperative objects.
In FP there is a very powerful distinction between behaviors and data. Behaviors are functions; data are immutable values. Functions use values, which may be functions, but never ever does a value contain a set of functions that mutates it like we do in OOP. In FP, we first model the data to convey the business requirements and constraints in a readable and maintainable way, enforced as much as possible by the compiler. We do it by defining our ADTs and other immutable types. **This is the data part** . Then, we move to the **behavior part** and create pure functions that use these immutable, possibly ADT-based values. These pure functions implement choices and logic. That’s the process we undertook in the `Artist` example.
THIS IS BIG!
In FP, behaviors are separated from the data model.
Now, it’s time to move on to the behavior part of this chapter. You’ve learned everything you need to create safe, readable, and maintainable data models in your applications. Newtypes and ADTs will get you very far, I promise. But to be good at design, you need to design things and a lot of them. **Practice is the key here.** \* So before we move on to modeling behaviors (pure functions), let’s do a design exercise!
\* The remaining part of this chapter contains two design exercises that should give you a lot of perspective on these somewhat simple, yet powerful, tools and techniques. Please approach them diligently.
## Coffee break: Functional data design 
It’s about time you design something of your own from scratch, using the ideas we’ve discovered in this chapter: newtypes and ADTs. This chapter is very musical at its core. Remember that, just like a melody defines a catchy song, we need a great design to have a catchy data model. Since we’ve just modeled a music artist, now your task is to model a playlist . | 1 |
Requirements 
1. Playlist has a name, a kind, and a list of songs.
2. There are three kinds of playlists: curated by a user, based on a particular artist, and based on a specific set of genres.
3. A song has an artist and a name.
4. A user has a name.
5. An artist has a name.
6. There are only three music genres: use your three favorite genres.
Your answer should be a `Playlist` type that models the above requirements in a readable way. The majority of work in this exercise is weighing different choices and naming things. I encourage you to prototype it yourself and experiment with the model by trying to create different values, business-wise. Looking at type definitions gives a lot of perspective. Remember that newtypes, ADTs, and the compiler are your friends. Keep a wary eye on the problems we want to avoid.
Here are few examples of playlists to test:
- A playlist named “This is Foo Fighters,” which is a playlist based on a particular artist (Foo Fighters) with two songs: “Breakout” and “Learn To Fly.”
- A playlist named “Deep Focus,” which is a playlist based on two genres (funk and house) and has three songs: “One More Time” by Daft Punk and “Hey Boy Hey Girl” by The Chemical Brothers.
- A playlist named “
’s playlist,” which is a user-based playlist.
Your second task is to use the Playlist model you’ll have created inside a new function called gatherSongs , which should have the following signature: | 2 |
```
def gatherSongs(playlists: List[Playlist], artist: Artist,
genre: MusicGenre): List[Song]
```
It should return some songs from given `playlists` , namely, songs performed by the `artist` from user-based playlists plus all songs from `artist` -based playlists plus all songs from `genre` -based playlists.
Hint: This may be a little bit harder than usual. The return type is a `List[Song]` , so the `filter` function won’t cut it! Still, you’ve already learned everything to solve this one!
## Coffee break explained: Functional data design 
There are multiple ways to model the `Playlist` . The most important point of this exercise is to create as readable and as bulletproof a design as possible, using ADTs and newtypes. Here’s one of the possible solutions:

## Modeling behaviors
Let’s go back to our original problem: searching through music artists. We solved three problems with our data using a newtype and ADTs.
Problem 1 ✔ Solved by the newtypes. Programmers need to be careful about the order of parameters . | Problem 2 ✔ Solved by ADTs. Programmers need to know an additional meaning of parameter combinations . | Problem 3 ✔ Solved by ADTs. Programmers need to ensure that some parameters have a finite set of values. Solved by ADTs . |
But we are still not done! When we look back at our requirements, we can see that we haven’t focused on a big part of them. Specifically:
Each search **should support a different combination** of conditions: by genre, by origin, and by period they were active in.
We focused on the `Artist` data model and moved from using primitive types to a bulletproof functional model. The compiler joined our efforts and now has got our backs. However, we ignored our search logic—the behavior that uses this data model. We just encoded behaviors as parameters of the `searchArtists` function and switched to using `MusicGenre` and `Location` along the way, but nothing more changed. Now, we face problems similar to the ones we’ve already solved when modeling data.
**Primitive type–based behavior** Function parameters are still problematic.
```
def searchArtists(artists: List[Artist], genres: List[MusicGenre],
locations: List[Location], searchByActiveYears: Boolean,
activeAfter: Int, activeBefore: Int): List[Artist]
```
Problem 4
**Programmers need to come up with, understand, and convey additional meanings to parameter types** .
What does genres: `List[MusicGenre]` mean in the `searchArtists` signature? If it’s empty, it means we shouldn’t search using the genre criteria. If it’s not empty, it means this is a required criterium: returned artists should have at least one of the genres on the list. See how much explanation is needed? It’s an explanation that is not conveyed by just writing genres: `List[MusicGenre]` because it’s just a list of `MusicGenre` that is not very descriptive in the context of searching for artists.
Problem 5
**Programmers need to remember that some parameters only make sense when used together** .
The `activeAfter` and `activeBefore` parameters can only be used together. They both implement the requirement to “filter artists that were active in the given period.” Additionally, they are only applicable when `searchByActiveYears` is `true` . So as you can see, there is a lot of semantic bundling of different parameters, which, again, is not directly explainable by looking at the function signatures and product type definitions.
## Modeling behaviors as data
The good news is that we can reuse what we learned about data modeling and apply exactly the same techniques to behavior modeling. The key is to start treating requirements as data . Thus, a search condition from requirements can be one of three things: a search by genre, a search by origin, or a search by activity period. We can directly translate the previous sentence from English to Scala by creating a sum type: | |
```
enum SearchCondition {
case SearchByGenre(genres: List[MusicGenre])
case SearchByOrigin(locations: List[Location])
case SearchByActiveYears(start: Int, end: Int)
}
```
Surprised? But how are we going to use this new `SearchCondition` type? Is it really better than the previous version? We needed to support different combinations of conditions, meaning that some searches may just use one condition and not others. How can we model this? Well, a list seems like a perfect fit! Have a look:
```
def searchArtists(artists: List[Artist],
requiredConditions: List[SearchCondition]): List[Artist] =
artists.filter(artist => ???)
```
A bit cleaner and more readable, don’t you think?
```
searchArtists(artists, List(
SearchByGenre(List(Pop)),
SearchByOrigin(List(Location("England"))),
SearchByActiveYears(1950, 2022))
)
List(Artist("Bee Gees", Pop, Location("England"), ActiveBetween(1958, 2003)))
```
If we want to use just some conditions, we need to include only them on the list:
```
searchArtists(artists, List(SearchByActiveYears(1950, 2022))) ①
searchArtists(artists, List(SearchByGenre(List(Pop)),
SearchByOrigin(List(Location("England"))))) ②
searchArtists(artists, List.empty) ③
```
① One condition
② Two conditions
③ No conditions
It’s impossible to misplace any parameters, there are no hidden handling cases for empty lists, all parameter combinations are encoded inside product types that are correctly named, and the function has fewer parameters. **Win–win–win!** Notice how we used verbs in type names. This is a common pattern that indicates that we model behaviors as data. From the client side, we can see how much more readable and understandable this new API is. Fewer mistakes are possible, and all the necessary meanings are conveyed. Surely, there must be a catch, right?
THIS IS BIG!
In FP, some behaviors can be modeled as data.
## Implementing functions with ADT-based parameters
There is no catch, really. These tools are really that good. However, it’s important to understand that the hardest part of both data and behavior modeling remains the same: it’s your job as a programmer to understand business requirements and encode them as newtypes and ADTs. Now, let’s see how to refactor `searchArtists` to this new, safer API.
❶ | As always, we start with the signature.We see that we get a List[Artist], and we need to return List[Artist]. It’s filtering! |
```
def searchArtists(artists: List[Artist],
requiredConditions: List[SearchCondition]): List[Artist] =
artists.filter(artist => ???) ①
```
① We need to return a Boolean true if all conditions in requiredConditions are satisfied by a given artist and false if at least one of them isn’t.
❷ | We can use forall! It will go through each of the conditions, and apply the function we pass as an argument. |
```
def searchArtists(artists: List[Artist],
requiredConditions: List[SearchCondition]): List[Artist] =
artists.filter(artist =>
requiredConditions.forall(condition => ???) ①
)
```
① How can we check whether this Artist satisfies a SearchCondition, which is an ADT?
❸ | If a value is an ADT, we can always use a pattern match to provide an expression for each condition. |
```
def searchArtists(artists: List[Artist],
requiredConditions: List[SearchCondition]): List[Artist] =
artists.filter(artist =>
requiredConditions.forall(condition => ①
condition match { ②
case SearchByGenre(genres) => genres.contains(artist.genre)
case SearchByOrigin(locations) => locations.contains(artist.origin)
case SearchByActiveYears(start, end) => wasArtistActive(artist, start, end)
}
)
)
```
① We need to destructure the condition and provide a behavior for each possibility.
② Remember that the compiler will make sure that we’ve handled all the possible conditions!
That’s it! A safe, readable, and maintainable version of searchArtists created by using ADTs to encode behavior requirements. Now, we have two parameters instead of seven, no primitive types, no nested if conditions, no Boolean flags—only the code that’s really needed. Additionally, we’ve used the power of two higher-order functions: filter and forall . To handle the ADT parameter inside the function passed to forall , we used the pattern-matching syntax. | Problem 4 ✔ Solved by ADTs Problem 5 ✔ Solved by ADTs |
I hope you are not tired of ADTs because we will use even more of them in the following chapters. We will also pay more attention to modeling from now on. That’s what the final exercise prepares you for!
## Coffee break: Design and maintainability 
We’ve shown how to design the `Artist` data model and `searchArtists` behavior so that they implement given requirements in a safe (i.e., minimizing programmer’s mistake risk) and readable way. We argued that designing this way also improves the maintainability of a codebase. And since maintainability of a given piece of software is defined as the ease of making amendments (fixes or new requirements), now it’s time to put our money where our mouth is and find out how easy would it be to build some new features into our existing solution.
New requirements
- Change in the model—Support the fact that some artists take breaks. For example, the Bee Gees were active from 1958 to 2003 and then from 2009 to 2012.
- New search condition—The `searchArtists` functions should handle the new search condition: return artists that have been (or were) active for a given number of years (in total).
**Your task in this final exercise of the chapter is to use all the tools, techniques, and superpowers we’ve learned to modify the** `Artist` **model and** `searchArtists` **behavior.** They should accommodate the new changes, defined as requirements above. Here are the current signatures of the `Artist` model and the `searchArtists` function:
```
case class Artist(name: String, genre: MusicGenre,
origin: Location, yearsActive: YearsActive)
def searchArtists(
artists: List[Artist],
requiredConditions: List[SearchCondition]
): List[Artist]
```
Do you think these signatures need to change to accommodate the new requirements or not?
Tips and Hints
Make sure to work this problem out yourself before looking at the answer. Modeling is hard, but getting it right is very rewarding. Here are some hints if you’ve gotten stuck:
1. Write down all the possibilities directly from requirements, and see if they may form a sum type. This will be your starting point.
2. Test your model first by creating instances. Notice how easy it is to create new values and how much the compiler helps. \*
3. Then, test your model by using it in a function. If it’s hard, remodel, refactor, and start over.
\* As always, running `sbt console` from the book’s code repository is your friend!
## Coffee break explained: Design and maintainability 
Congratulations! This was the hardest exercise in the book, and I am sure you learned a lot while trying to finish it. As with other design exercises, there are multiple good ways to solve it. Here’s one of the possible designs:

## Summary
In this chapter we learned about newtypes and **ADTs** (which are **sum types** implemented in Scala as `enums` and/or **product types** implemented as `case classes` ). We learned about **pattern matching,** which helps us handle ADTs in our pure functions (behaviors). We approached the problem of code duplication and compared ADTs to object-oriented inheritance. We also learned a handful of new higher-order functions that are very versatile. They are defined on `Options` , `Lists` , and many more types. But most importantly, we learned how to use all of these techniques as design tools.
ADT stands for algebraic data type.
CODE: `CH07_*`
Explore this chapter’s source code by looking at `ch07_*` files in the book’s repository.
Model our immutable data to minimize errors
We learned that the fewer primitive types we use, the fewer problems we may encounter later on. It’s always good to wrap a type in a newtype or use a more business-oriented ADT. That’s how we minimize potential mistakes.
Model our requirements as immutable data
We found out that we can use ADTs as parameters to our functions and make both the signatures and implementations a lot safer and more readable.
Also, we used the `Option` type as a part of the model, which is a totally different context than what we’ve seen previously. Remember that so far we’ve used `Option` as a return type that hinted a function may not return or compute a value.
Find problems in requirements using the compiler
We upgraded our friendship with the compiler to the next level. It helped us a lot when we started using newtypes and ADTs instead of primitive types.
Make sure our logic is always executed on valid data
We addressed a concern similar to the one from the previous chapter. But we didn’t really need full-blown runtime-error handling like the one introduced there, which used `Either` . We didn’t need it because we modeled the requirements in such a great detail—using types—that it was impossible to even instantiate many incorrect values. This so-called compile-level _error handling_ is far superior to the runtime version, though it is not always possible.
ADTs and `Either` can be used for similar purposes, as we’ll see in chapter 12.
We will come back to this topic later in chapter 12.

These techniques are ubiquitous in FP. They are simple and very powerful, just like pure functions, immutable values, and higher-order functions. That’s why we spent so much time practicing different approaches to software design and showing the advantages of functional domain design. Now, we are going to reap the benefits of all this hard design work because, as it turns out, ADTs are going to stay with us for a long time. (Well, they’ve been with us since the beginning in the form of `List` , `Option` , and `Either` —yes, these are ADTs too—but let’s not get ahead of ourselves!) Next stop: IO!