Clojure multi-methods

When I first heard of Clojure and functional programming, I thought it was much more limited than it is. This is probably due to the strange look of it with all the brackets and it’s lack of objects, but actually it’s not so bad.

I have learned that many of the tools available to you in Object Oriented Programming are available to use in Clojure. One of these is polymorphism. The way that it works is very different, but the fact that it exists at all is quite cool.

A multi-method allows you to have different behaviour for methods with different arguments. In order to have multi-methods, firstly you need to define the common name.

(defmulti greeting :name)
(defmethod greeting "Alan" [] "Hi Alan!")
(defmethod greeting "Eric" [] "Hi Eric! Please check-in as soon as possible.")

Here calling:

(greeting {:name "Eric"}) 

will return “Hi Eric! Please check-in as soon as possible.

It does this through the use of a dispatching function. You don’t need to have a function and can just return the argument itself (like I have done above). It’s really the value that is passed to the method (which is processed or not) that determines which method to run.

I was worried when I initially used my multi-methods that they are another form of branching ifs which in OO programming is a code smell, but ultimately they actual act in a similar way but are much easier to read.