4 ms·
Introduction to Protocols in Clojure
- MBlume 13y agoIs there a good explanation somewhere of protocol internals -- what it looks like in the JVM when a protocol member is called/what bytecode is generated from a protocol extension?
- wging 13y agoIf no one replies with a good answer, then your best bet might be https://github.com/clojure/clojure/tree/master/src https://github.com/clojure/clojure/tree/master/src . (I acknowledge this isn't really an answer to your question.) I will try to find the implementation of protocols in here for you... Edit: a start might be 'defprotocol' in https://github.com/clojure/clojure/blob/master/src/clj/clojure/core_deftype.clj https://github.com/clojure/clojure/blob/master/src/clj/cloju...
- Skinney 13y agoIt depends. You implement a protocol while defining a record or type, so called inlined implementation, then it's the same as a Java class with a implemented interface. Clojure allows extending protocolls outside a record/type definition though. This allows you to extend protocolls to classes/types you haven't declared, like Clojure map. I'm uncertain how that is implemented though.
- weavejester 13y agoThe examples in the introduction are a touch contrived, because if you don't need polymorphism, you shouldn't really be using protocols. In the examples provided, it would be more idiomatic to use normal functions.
- moomin 13y agoIndeed. Also, there's a lot of different approaches to polymorphism in Clojure, all of which are valid in context. Protocols are fast but quite limited. Personally, I find it better to start with the freedom of multimethods for several reasons: 1) Protocols push you down OO roads 2) It could be a premature optimization 3) Multimethods are brilliant for discovering the most elegant design. The last point bears expanding on: multimethods don't bundle methods together, allow hierarchies not based on Java's inheritance, can dispatch on arbitrary strategies. Going protocol too early tends to lead to too many concrete types and not enough straight-forward data manipulation. Which is not to say that protocols aren't brilliant. It's just that it looks like the first tool you should reach for and it's probably the last. Note the article is from 2010, when protocols were the new shiny.