Combining Clojure defprotocol and defrecord

依然范特西╮ 提交于 2019-12-19 03:10:24

问题


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?


回答1:


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.




回答2:


Yes that is completely correct :)

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



来源:https://stackoverflow.com/questions/6627020/combining-clojure-defprotocol-and-defrecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!