Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function map vs protocol implementation

Tags:

idioms

clojure

I'm new to clojure and I'm trying to make sense of the different design choices available in different situation. In this particular case I would like to group tightly coupled functionality and make it possible to pass the functions around as a collection.

  1. When to use function maps to group tightly related functionality and when to use protocols (+ implementations)?

  2. What are the advantages and drawbacks?

  3. Is either more idiomatic?

For reference, here are two examples of what I mean. With fn maps:

(defn do-this [x] ...)
(defn do-that [] ...)
(def some-do-context { :do-this (fn [x] (do-this x)
                       :do-that (fn [] (do-that) }

and in the second case,

(defprotocol SomeDoContext
  (do-this[this x] "does this")
  (do-that[this] "does that")

(deftype ParticularDoContext []
  SomeDoContext
  (do-this[this x] (do-this x))
  (do-that[this] (do-that))
like image 796
4ZM Avatar asked Jul 18 '26 00:07

4ZM


1 Answers

It all depends on what you meant by "tightly related functionality". There can be 2 interpretations:

  • These set of functions implement a particular component/sub-system of the system. Example: Logging, Authentication etc. In this case you will probably use a clojure namespace (AKA module) to group the related functions rather than using a hash map.

  • These set of functions work together on some data structure or type or object etc. In this case you will use Protocol based approach, which allows ad-hoc polymorphism such that new types can also provide this set of functionality. Example: Any interface kind of thing: Sortable, Printable etc.

like image 178
Ankur Avatar answered Jul 20 '26 12:07

Ankur