While defrecord
is the preferred form -for the general case- in Clojure for defining an "entity", in ClojureScript one can find far more references to deftype
, as reflected in various documentation.
What is the difference between both forms? Which should one prefer?
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.
deftype
creates a bare-bones object which implements a protocol.
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? Then use a type.
The two bits of documentation you reference use types because they're trying to illustrate protocols at the most basic level, and types have less "going on" than records, so to speak.
However, most real-world uses of object-like things in Clojure/ClojureScript need to store fields of data along with the object, and for that you should emphatically use a record, for the same reason you should use any of Clojure's immutable collections.
According to DEFTYPE VS DEFRECORD, you should distinguish programming constructs and domain constructs.
deftype
is for programming constructs and defrecord
is for domain constructs that need a custom type.
Hope this helps.
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