defmulti vs defprotocol?
Asked Answered
M

2

8

It seems like both can be used to define functions that you can implement later, with different data types. AFAIK the major difference is that defmulti works on maps and defprotocol works on records.

What other differences there? What are the benefits of using one over the other?

Markland answered 18/1, 2012 at 9:47 Comment(0)
C
16

Short version: defmulti is much more flexible and general, while defprotocol performs better.

Slightly longer version:

defprotocol supports dispatch on type, which is like polymorphism in most mainstream programming languages.

defmulti is a more general mechanism where you can dispatch on other things than just a single type. This flexibility comes with a performance penalty.

More on protocols

More on multimethods

Chenoweth answered 18/1, 2012 at 9:56 Comment(2)
Aha, thank you! It also seems that the functions don't need to be declared together, like extend-type requires. Is this correct?Markland
You can think of a protocol as a Java interface. So with defprotocol you need to declare the functions together. A multimethod declaration is a single thing, but the defmethod definitions don't have to be together.Chenoweth
N
5

Just an addition to cover the motivation, corvuscorax's answer covers the origional question nicely.

Originally Clojure only had multimethods and very early on a lot of thought went into building a dispatch abstraction that could handle all cases very well and would not force people to structure their abstractions around a limitation of the abstractions offered by the language.

As Clojure matured the desire to create "clojure in clojure" required abstractions that where at least in theory capable of producing any bytecode that could be produced by java and thus the need for protocols, a dispatch abstraction that more closely matched native Java.
Clojure has a strong "embrace your platform" ideal and protocols suit this mindset very well.

Numinous answered 19/1, 2012 at 2:37 Comment(2)
I see. So what is the benefit of writing Clojure in Clojure?Markland
One reason is to be able to write Clojure at a higher level of abstraction. Kind of like writing a C compiler in C, instead of in assembly. This would also make things like ClojureScript easier to do, and make it easier to keep the CLR port of Clojure in sync with the JVM version. Plus, it's cool and elegant in a Gödel, Escher, Bach-ish way :-)Chenoweth

© 2022 - 2024 — McMap. All rights reserved.