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 sti开发者_如何学编程ll 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?
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.
Yes that is completely correct :)
The main reason for this would be if you expect others to want to extend your protocol later.
精彩评论