Clojure: multimethods versus protocols

Context

Recently, I have been writing a lot of code that uses several methods and protocols.

I find that most of my multimethods are one dispatch — they depend only on the type of one of the arguments.

These are situations when multimethods can actually be replaced by adding an additional field to the protocol.

Question

In situations where instead of a multimethod, instead of a protocol, you can replace a protocol, is there any reason to use multimethod instead?

Thanks!

+8
clojure
source share
3 answers

I usually prefer protocols : they offer better performance and do a great job with the general case (separate sending by type).

Sometimes you really need a more complicated submission, in which case you can:

  • Go through the whole pig and use multimethods
  • Write a short piece of custom code (usually (cond .....) ) to handle sending. This is sometimes better than multimethods because, for example, multimethods do not handle value ranges very well.

A useful additional tip is to write your main (publicly exposed) functions in such a way as to delegate the corresponding protocol function.

eg. it could be something like:

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

This gives you great flexibility to further modify your internal implementation without requiring extensive refactoring or affecting the calling code.

+2
source share

You can use the multimethod if there is a reasonable probability that your requirements will change, and you will need to use several dispatchers in the future.

Otherwise, you must approve the protocols when they are sufficient for your purposes.

+2
source share

Personally, I prefer multimethods, as they separate presentation from behavior more efficiently than protocols. Beyond performance, I see no reason to sacrifice the ability to use simple maps to represent my data, add multiple mailings as needed, or send them by properties other than the "physical" type (which in itself is not a big concept to rely on, in my opinion )

+2
source share

All Articles