Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Clojure defprotocol and defrecord

As far as I can tell, if I want to define a protocol (defprotocol) that will only be implemented by one defrecord, I still have to define the protocol first, then define the defrecord that implements it:

(defprotocol AProtocol
  (a-method [this])
  (b-method [this that]))

(defrecord ARecord [a-field b-field]
  AProtocol
  (a-method [this] ...)
  (b-method [this that] ...))

Is there no way to combine the two, perhaps with an "anonymous" protocol?

like image 571
Ralph Avatar asked Jul 08 '11 15:07

Ralph


2 Answers

Don't do this. A "private" or "anonymous" protocol that your record implements is just reinventing a pointless version of OOP in a language that has better options. Define a regular old function that operates on your records; there's no reason it has to be physically attached to them.

If you later want to refactor it to be a protocol instead...it's easy! The client won't be able to tell the difference, because protocol function calls look just like regular function calls.

like image 93
amalloy Avatar answered Nov 04 '22 08:11

amalloy


Yes that is completely correct :)

The main reason for this would be if you expect others to want to extend your protocol later.

like image 43
Arthur Ulfeldt Avatar answered Nov 04 '22 08:11

Arthur Ulfeldt