7 Designing programs with function composition

 

This chapter covers

  • Defining workflows with function composition and method chaining
  • Writing functions that compose well
  • An end-to-end example of handling server requests

Function composition is not only powerful and expressive but also pleasant to work with. It’s used to some extent in any programming style, but in FP, it’s used extensively. For example, have you noticed that when you use LINQ to work with lists, you can get a lot done with only a few lines of code? That’s because LINQ is a functional API, designed with composition in mind.

In this chapter, we’ll cover the basic concept and techniques of function composition and illustrate its use with LINQ. We’ll also implement an end-to-end server-side workflow in which we’ll use the Option API introduced in chapter 6. This example illustrates many of the ideas and benefits of the functional approach, so we’ll end the chapter with a discussion of those.

7.1 Function composition

Let’s start by reviewing function composition and how it relates to method chaining. Function composition is part of any programmer’s implicit knowledge. It’s a mathematical concept you learn in school and then use every day without thinking about it too much. Let’s quickly brush up on the definition.

7.1.1 Brushing up on function composition

Given two functions, f and g, you can define a function h to be the composition of those two functions, notated as follows:

h = f · g

7.1.2 Method chaining

7.1.3 Composition in the elevated world

7.2 Thinking in terms of data flow

7.2.1 Using LINQ’s composable API

7.2.2 Writing functions that compose well

7.3 Programming workflows

7.3.1 A simple workflow for validation

7.3.2 Refactoring with data flow in mind

7.3.3 Composition leads to greater flexibility