“polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface” -Wikipedia
In most Object Oriented programming languages, polymorphism is tied to inheritance. In Clojure however, the concept of concrete inheritance is not built into the language. So, when I was first learning Clojure, it was hard for me to use my previous knowledge of polymorphism in the functional world. No need to fear, Clojure provides great methods for achieving polymorphism without using concrete inheritance.
As an example, this is a simple function that takes basic Clojure data and converts it to JSON.
This works, but it is not polymorphic. So let's take a look at a few ways to improve this.
A Clojure multimethods is a combination of a dispatch function and one or more methods, each defining its own dispatch value. The dispatching function is called first, and returns a dispatch value. This value is then matched to the correct method. Lets take a look at our previous example refactored into a multimethod.
Awesome! We have our first polymorphic solution. Now we can add more data types without altering the existing functions. Let's add a method for vectors as well.
Now we can also convert vectors into JSON.
There is another feature of multimethods that we can use to extend this solution further. Multimethods actually use the
isa? function instead of the
= function to match dispatch values to the correct method. This yields a very important feature, hierarchies. Let's open up the REPL and take a look at the classic Shape example,
Now let's see if we can apply this hierarchy system to our previous vectors method.
With this hierarchy, any type that matches
::collection will dispatch to the same method as vectors. Since there is no difference between a list and vector in JSON, we can convert them to JSON in the same way, so we simply make PersistentList derive from
::collection as well.
We were able to extend the multimethod to handle Lists with one line!
Its also worth noting that we could implement the same functionality without introducing hierarchies here. List and vectors already share many common interfaces, so we could use one of those instead. We simply replace our vector method with this
Now we’re able to convert vectors and lists without using hierarchies.
Another great feature that is hard to demonstrate here is that the methods do not have to be defined in the same file as their dispatch function. This allows us to extend the functionality of multimethods that are defined elsewhere in the system or even in a 3rd party library.
Multimethods can be very useful in situations where you cannot change the clients of a function. For instance, if there are thirty other functions using the convert function, it is hard to change. However, we can refactor into a multimethod without changing any of the clients. This allows us to refactor safely without affecting any clients.
In my experience, multimethods are best used in cases where you only need to define one polymorphic function. When multimethods are used to define a group of polymorphic methods, this solution can get a little messy. However, Clojure provides great facilities for this as well, namely Protocols.
Another way to improve our original switch statement is though Protocols. Protocols will be a little more familiar for those coming from Object Oriented languages, as they are very similar to interfaces. Let's look at our original function refactored to use a Protocol.
In this example, we define a Protocol, JSON, which has one method, to-json. Then we use the helper macro extend-protocol to extend all of our types at once. Now, we can simply call the to-json method directly on the data types themselves rather than through a conversion function.
In the same way that interfaces are used in conjuction with classes in Java and C#, protocols, in conjunction with deftype or defrecord, can be used to define an explicit API that a type implements. For example,
Using this method, we can kind of mimic objects. Terrier can be instantiated and used just like any other object.
Even though I don’t like mimicking objects in Clojure, sometimes it is necessary in order to use Java interfaces and objects, which you can learn more about here.
As with multimethods, type definitions do not have to be defined in the same file as their protocol definition, allowing us to implement protocols defined in other libraries.
As seen in the Dog/Terrier example, Protocols are great for encapsulating a group of related methods into one polymorphic package. However, this method of polymorphism should be used sparingly. Protocols are often abused to mimick an Object Orient approach because it is a familiar solution. However, if you do this, you will often miss out on the simplest solution, pure functions.
Functions as parameters
This is simplest form of polymorphism in Clojure. By accepting a function as a parameter, the given function proide multiple solutions with one interface (the parameters). Instead of refactoring our original function, let's consider a context in which it is commonly used. Web servers often need to convert data structures into JSON before returning them to clients. So let's consider a resource controller, which has an action to create a User given the request parameters.
This function simply takes the request params, builds a user model out of them, saves them to the database and returns the result as JSON. We can make this controller polymorphic by accepting the JSON converter function as a parameter to the create function instead of calling it directly.
Now the create function doesn’t have to know anything about the structure of the data that is returned to the user. The given converter function is polymorphic, meaning that it can convert the data into whatever format the user requests, instead of just JSON. So if the user requests XML or HTML instead of JSON, we don’t need to alter our create function; we simply need to pass in a different converter.
Using functions as parameters is by far my favorite form of polymorphism in Clojure. It is this simplest and most consise of all three methods; I try to use this method whenever possible. However, Multimethods and Protocols are equally powerful and provide useful ways in which to design polymorphic systems without concrete inheritence. With these methods in your tool belt, you don't have to feel as lost as I did when coming into the world of Clojure.