Lesson 13. Achieving code reuse in F#
We’re going to change tack a little in this lesson, and look at using functions (and type inference) in F# to create lightweight code reuse, and to pass functionality (rather than data) through a system. If you’ve used the LINQ framework at all, much of this lesson will be familiar to you. We’ll cover
- How we tend to achieve reuse in the OO world
- A quick review of the core parts of LINQ
- Implementing higher-order functions in F#
- Dependencies as functions
We always look to reuse code in our applications, because copy-and-paste is evil—right? Unfortunately, you know as well as I do that reuse at a low cost is sometimes really hard to achieve! There are many types of code reuse that we strive to achieve; this lesson focuses on a common form of reuse, although the outcomes from this lesson can be applied across most forms of reuse.
Let’s imagine that you have a collection of customers, and need to filter out some of them based on logic that you don’t yet know. In this case, it might be “Is the customer female,” but at some point, you might need to write other types of filters, and you don’t want to reimplement the logic of “filtering over the customers” every time you need a new filter. What you need is a way to separate out the two pieces of logic, but then combine them together as needed (see figure 13.1).