Chapter 4. Multimethod polymorphism
This chapter covers
- Polymorphism and its types
- Clojure multimethods for ad hoc polymorphism
- Using multi-argument dispatch
- Querying, modifying, and creating dispatch hierarchies
You should now know how to use Clojure’s types and functions and even write some fairly advanced higher-order functions, but you may still be wondering how to build larger systems with functional programming. In this chapter, you’ll learn how to use the most powerful and flexible tool Clojure has for creating and using abstractions in large programs: multimethods.
Polymorphism is the ability to use multiple types as though they were the same—that is, you can write the same code to operate on many different types. This kind of abstraction allows you to substitute different types or implementations without having to change all code that touches objects of those types. Polymorphism’s ability to reduce the surface area between different parts of a program and easily substitute some parts for other parts is what makes some form of it essential in larger systems. In a certain sense polymorphism provides the ability to create your own abstractions.
There are multiple ways to achieve polymorphism, but three are common to many languages: parametric, ad hoc, and subtype polymorphism. We’ll concentrate on what these look like in Clojure without multimethods but also glance at how other languages achieve the same kinds of polymorphism.