4 Designing function signatures and types

 

This chapter covers

  • Designing good function signatures
  • Fine-grained control over the inputs to a function
  • Using Unit as a more flexible alternative to void

The principles we’ve covered so far define functional programming in general, regardless of whether you’re programming in a statically typed language like C# or a dynamically typed language like JavaScript. In this chapter, you’ll learn some functional techniques that are specific to statically typed languages: because both the functions and their arguments are typed, this opens up a whole set of interesting considerations.

Functions are the building blocks of a functional program, so getting the function signature right is paramount. And because a function signature is defined in terms of the types of its inputs and outputs, getting those types right is just as important. Type design and function signature design are really two faces of the same coin.

You may think that, after years of defining classes and interfaces, you know how to design your types and your functions. But it turns out that FP brings a number of interesting concepts to the table that can help you increase the robustness of your programs and the usability of your APIs.

4.1 Designing function signatures

A function’s signature tells you the types of its inputs and outputs; if the function is named, it also includes the function’s name.

4.1.1 Writing functions signatures with arrow notation

4.1.2 How informative is a signature?

4.2 Capturing data with data objects

4.2.1 Primitive types are often not specific enough

4.2.2 Constraining inputs with custom types

4.2.3 Writing “honest” functions

4.2.4 Composing values with tuples and objects

4.3 Modeling the absence of data with Unit

4.3.1 Why void isn’t ideal

4.3.2 Bridging the gap between Action and Func

4.4 Summary