Yesterday, Rich pulled the 'new' branch of Clojure into master. We are now embracing the beauty that is deftype and defprotocol. Of course, I, coming from Haskell, am very tempted to define types like I would in Haskell, which would be for virtually everything short of a throwaway tuple, but I don't think it works like that in Clojure world ;). In the Common Mistakes thread for Clojure, one guy mentioned that overusing structs was a mistake he made when he first started, coming from OOP. Since deftypes seem to be similar to structs, I was wondering if the same thing applies there.
So, my question is: when is it a good time to use deftype?
Summary: There are two commonly used ways to create new data types in Clojure, deftype and defrecord . They are similar but are intended to be used in two distinct use cases. deftype is for programming constructs and defrecord is for domain constructs.
defrecord creates an immutable persistent map which implements a protocol. Which to use depends on what you want. Do you want a full ClojureScript data structure? Then use a record. Do you just want a bare-bones thing that does nothing but satisfy a protocol?
Clojure has gen-class, reify, proxy and also deftype and defrecord to define new class-like datatypes.
A protocol is a named set of named methods and their signatures, defined using defprotocol: (defprotocol AProtocol "A doc string for AProtocol abstraction" (bar [a b] "bar docs") (baz [a] [a b] [a b c] "baz docs")) No implementations are provided. Docs can be specified for the protocol and the functions.
One area deftype
shines is performance. Methods of protocols are very fast on a deftype. Also deftype may have primitive fields, so no boxing anymore when crunching numbers...
Another area might be Java interoperation, since deftype can implement interfaces (and if AOT compiled) have a named class.
In general is the basic idea to define abstractions with protocols and to implement them with deftype.
Rich details his motivation here: http://www.assembla.com/wiki/show/clojure/Datatypes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With