Clojure: multimethods vs protocols

clojure

Solution

I normally prefer protocols: they offer better performance and handle the common case (single dispatch on type) very well.

Sometimes you will genuinely need more sophisticated dispatch, in which case you can either:

- Go the whole hog and use multimethods

- Write a short piece of custom code (typically a `(cond .....)`) to handle the dispatch. Sometimes this is better than multimethods, because e.g. multimethods don't handle ranges of values very well.

A useful extra piece of advice is to write your main (publicly exposed) functions in a way that delegate to the appropriate protocol function.

e.g. it might be something like:

(defn my-api-function [a b]
  "Do interesting things with a and b"
  (multimethod-function
    (protocol-function a)
    (protocol-function b)))

This gives you plenty of flexibility to change the internal implementation later, without requiring extensive refactoring or affecting calling code.

Problem

Context I have been writing lots of code involving multimethods and protocols lately. I find that most of my multimethods are single dispatch -- they only depend on the type of one of the arguments. These are situations where the multimethods can actually be replaced by adding an extra field to the protocol instead. Question In situations where a multimethod can be replaced with a protocol instead, is there any reason to use multimethod instead of protocol? Thanks!

Original source