practicalli / practicalli/clojure

To protocol or not to protocol?

Open
#121 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Makefile
Stars
117
Forks
36
PR merge metrics
No merged PRs in 30d

Description

I really like protocols, but the community seems to advise against using defrecord. Is there a way to conciliate the two tools?

Well, it's not that you shouldn't use defrecord or protocols. Its more that you should only use them when they are really needed

What people try to advise against is using defrecord and protocol as a means to replicate classes

It's too easy with them to think of your protocol as methods that operate over the records, which is basically what a class/object is.

So what people say is, try not to use them for that. Only use protocols when you need polymorphism, that means that you have two records that both share functionality and you want the type of the record to be used to choose which implementation of the protocol to use.

Then you can use protocols and records.

I'd suggest for now if you want to model some entity like say a person. Just do this:

(defn make-person
  [{:keys [name age height]}]
  {:name name
   :age age
   :height height})(defn legal-age?
  [person]
  (> (:age person) 21))

Protocols are also useful when you want users of your library to plug into a feature you expose. For example, a WebSocket library may expose a Sendable protocol and you can implement that for your own types to be able to send your custom type across.

For me it was more that protocol allowed me to define operations on some kind collection that I know will be generic. For example: how can you implement the datafy protocol without record?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue contains a conceptual discussion of Clojure protocols, defrecord, and datafy, but names no repository files or tests. First clarify whether an explanatory documentation change is wanted and what guidance should be captured; done is a decided scope and a documented answer.

Written by the indexing model from the issue text.

Assessment

Tech stack
clojure
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.