Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deftype vs. defrecord

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?

like image 482
deprecated Avatar asked Oct 31 '12 02:10

deprecated


People also ask

What is Defrecord?

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?

Are there classes in Clojure?

Clojure has gen-class, reify, proxy and also deftype and defrecord to define new class-like datatypes.


2 Answers

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.

like image 199
levand Avatar answered Sep 30 '22 11:09

levand


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.

like image 25
Leo Avatar answered Sep 30 '22 09:09

Leo