How do I know when to use deftype, defrecords, and defmulti?


#1

Hello all. I have been learning about Clojure’s way of handling OOP and have to admit that I am kind of confused when to use deftype, defrecord, and defmulti. I would really like to know when and why to make a particular choice.
Thank you ahead of time :slight_smile:


#2

Hey @githier,

Good question.

defrecord and deftype are most similar. They both define new types (concrete classes) that hold state and can have methods. The difference is how you should use them. defrecord is used for building out domain types. If you’re building accounting software, you might use defrecord to represent a transaction. When you use defrecord, you get a definition of equals built in that works like hash maps.

deftype, on the other hand, is for building low-level types—classes that are not part of the domain. For instance, if you wanted to make a tree data structure, you would use a deftype. It doesn’t really apply to the business domain but it is useful in the implementation. deftype gives you very little built in, which is great for giving you complete control.

defrecord and deftype are often confused. But really, for domain objects people tend to use hashmaps. Why make a new type?

drfmulti is a different animal. It’s for defining a function that has multiple implementations, dispatched by a value. Just like methods in Java-like OO dispatch based on the type of object, multimethods can dispatch. However, they dispatch based on any calculable value from any of the arguments. defmulti is closest to defining a new method in an interface.

Thanks again for the question. Keep them coming.

Rock on!
Eric