Designing composable functions

Sometimes, you may hear other Julia programmers talk about composability. What does that mean? 

Composability is used to describe how easily functions can be assembled in different ways to achieve different results. Let's look at an analogy. I would say that Lego has a highly composable design. This is because almost every piece of Lego can be combined with any other piece of Lego, even if they have different shapes. For that reason, any kid can use Lego to build almost anything imaginable.

When it comes to system design, we can also keep composability in mind. If we could build our functions so that they can be composed easily, then we would have the flexibility to build many different things as well. In Julia, we can compose functions quite easily.

Let's use the same example from the previous section. We will create a new function called top_story_id that retrieves the first story ID from Hacker News:

From the preceding code, we can see that the top_story_id function is defined as an anonymous function. The Unicode circle symbol (, input as circ) is the compose operator in Julia. Unlike the pipe operator, we read the order of composed functions from right to left. In this case, we apply the fetch_top_stories function first and then apply the first function. Intuitively, we can use the top_story_id function as usual:

We can also compose multiple functions. To get the top story details, we can compose a new function called top_story, as follows:

This is great! We have taken three random Lego blocks and built a new thing out of them. The top_story function is a new thing that is composed of three smaller blocks:

Let's go one step further and create a new function to retrieve the title of the top story. Now, we run into a little trouble. No function that returns the story title from a Story object has been defined. However, we can solve this problem by utilizing the Accessors Pattern, which we described in Chapter 8, Robustness Patterns.

Let's define an accessor for the title field and then compose a new top_story_title function, as follows:

This new function works beautifully, as expected:

The compose operator allows us to create a new function that is composed of several other functions. It is slightly more convenient than the pipe operator in the sense that the composed function doesn't need to be executed right away.  

Similar to functional pipes, the compose operator also expects single-argument functions. Having said that, it is also the reason why single-argument functions are more composable.

Next, we will go back and revisit the Hacker News average_score function and see how we can refactor the code into the functional pipe style.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10