9 Structuring an application with functions

 

This chapter covers

  • Partial application and currying
  • Getting around the limitations of method type inference
  • Modularizing and composing an application
  • Reducing lists to single values

Structuring a complex, real-world application is no easy task. There are entire books written on the subject, so this chapter by no means aims to provide a comprehensive view. We’ll focus on the techniques that you can use to modularize and compose an application consisting entirely of functions, and how the result compares to how this is usually done in OOP.

We’ll get there gradually. First, you’ll need to learn about a classic but fairly low-level functional technique called partial application. This technique allows you to write highly general functions whose behavior is parameterized, and then supply those parameters, obtaining more specialized functions that have the parameters given so far “baked in.”

We’ll then look at how partial application can be used in practice to first specify configuration arguments that are available at startup, and purely runtime arguments later, as they’re received.

Finally, we’ll look at how you can take the approach one step further and use partial application for dependency injection, to the point of composing an entire application out of functions, without losing any of the granularity or decoupling you’d expect when composing it with objects.

9.1 Partial application: supplying arguments piecemeal

9.1.1 Manually enabling partial application

9.1.2 Generalizing partial application

9.1.3 Order of arguments matters

9.2 Overcoming the quirks of method resolution

9.3 Curried functions: optimized for partial application

9.4 Creating a partial-application-friendly API

9.4.1 Types as documentation

9.4.2 Particularizing the data access function

9.5 Modularizing and composing an application

9.5.1 Modularity in OOP

9.5.2 Modularity in FP

9.5.3 Mapping functions to API endpoints

9.5.4 Comparing the two approaches

9.6 Reducing a list to a single value

9.6.1 LINQ’s Aggregate method

9.6.2 Aggregating validation results

9.6.3 Harvesting validation errors

9.7 Exercises

sitemap