Why perform functions on records?

It is possible to implement protocols in records (and types for that matter). But I'm wondering if there is any reason for this if these specific features are only going to be implemented once (i.e. only for one post type), or if all posts use the same implementation of that particular feature.

To illustrate, let's say I have an entry for a player.

(defrecord Player [x y hp inventory])

      

Now I am given the opportunity to implement the update protocol;

(defprotocol Update
  (update [this world]))

(defrecord Player [x y hp inventory]
  Update
  (update [this world] this))

      

Or I could just write a separate function for this.

(defn update [player world] player)

      

Is there a difference between them, efficiency or something really?

+3


source to share


2 answers


  • A simple function definition update

    does not do type checking to make sure you only pass the profiles to it, but the protocol version of this protocol does, and IllegalArgumentException

    says, you might need that kind of tick security. Or you just want to tell others what argument is expected, but there are other ways to do this.

  • The protocol version is more complex, adding complexity that cannot serve any purpose. You may want to be able to easily define a simple function.

I think it is not uncommon in the Clojure world to prefer simplicity of expression over type safety when there is a trade-off between the two, but that depends on the project and the programmer. Personally, I usually want simpler code, but there are times when I lean in the other direction.

There are also the following obvious considerations:



  • The protocol version can confuse people as protocols are commonly used to allow polymorphic behavior, so they expected a protocol to be defined for multiple record types.

  • If you expect to need polymorphism in the future, you can customize your code to do this from the start using protocols.

Finally:

  • I have no answer regarding efficiency. Someone else has something helpful to say about this. However, you can run tests using Criterium to see if there is a difference for your code.
+2


source


This should be a comment on Mars' answer.



As for efficiency ... According to The Joy of Clojure 2nd ed. (Page 216 for the curious), calling a method with inline definition of protocol methods is several times faster than calling one of the objects that implement the protocol through an extension.

+1


source







All Articles