1. Why cleaner code?
In this chapter, we'll see how we can use purrr to write cleaner code.
But first things first, let's ask ourselves this question: why should we bother to write cleaner code in the first place?
2. Where's Waldo?
Let's have a look at this piece of code. Have you spotted the errors yet?
In this code, there are two typos: one in the name of a column on the second line, and one in the function name on line 4 — also, the "Sepal.Length" column appears twice.
Moreover, if we want to change the p.value threshold in the filter, we will have to do it four times using the current code.
So, here are the two big issues with this code: first, it's harder to spot typos as there is a lot of repetition, and it's harder to interpret what's going on in each line - our eyes are more focused on what is similar than on what is changing.
3. Finding Waldo
Let's now have a look at this new piece of code. For now, don't focus on the functions used: we'll see them in more detail throughout this chapter.
Just focus on the readability and the maintainability. It's much easier to interpret this code, and to maintain it: if we need to change something, for example, the p.value threshold, we will just have to do it once. Same goes for the na.action parameter, which defines the behavior of the lm() function if it en counters a missing value.
That's something you should always aim for when you are writing code: write code so that when in the future you'll need to change one thing, you'll just have to do it once.
4. What is clean code?
So, let's review what makes code clean.
First, it's light, in the sense that there should be no unnecessary code. Light code is easier to read: your eyes can more easily focus on the part of the code being executed if there is no repetition, rather than trying to read inside each repetition.
As there is no repetition, it's also easier to interpret: one bit of code, and one bit only is used to do one specific task.
In the end, this also helps you in the long run, as it is easier to maintain. Think about the moment when you will have to change something, such as fixing a bug or implementing a new feature, when using light and clean code; you just have to change things once.
5. compose()
The first function we will see is compose(), which, as its name suggests, is used to compose a new function from two other functions.
compose() is a tidyverse adverb: it takes a series of functions and returns a new function. This newly created function can be called like any other function.
6. Composing cleaner code
As you can see, thanks to the compose() function, the code on the bottom of this slide is cleaner. It is easier to read and understand, as there are fewer repetitions. And it is easier to maintain it, because if you need to change the content of your pipeline, you only have to do it once, instead of having to change the four nested functions.
7. Let's practice!
Now let's try to write better code with compose().