Clojure Best Practice: When to Use Metadata?

I do not mean this as a subjective question - I'm trying to understand why with-meta is in this language. I understand that it can be used for many purposes (so it can be eval , but using it outside of special circumstances is a sign of poor design). From a design point of view, what is the unique purpose of the Clojure metadata structure? Is this mainly for documentation? Is it sugar?

What are some powerful apps for with-meta / meta ? When is a bad idea? Can you give an example of using metadata to accomplish something that would be impossible / difficult / tedious without it?

+8
clojure
source share
1 answer

Some of the main functions of the language depend on metadata:

  • a macro uses one function, which depends on metadata. A macro is a function with a small amount of metadata that forces the function to run at compiletime.

     user> (meta #'when) {:macro true, :ns #<Namespace clojure.core>, :name when, :arglists ([test & body]), :column 1, :added "1.0", :doc "Evaluates test. If logical true, evaluates body in an implicit do.", :line 471, :file "clojure/core.clj"} 
  • Types are another feature of the language that depends on metadata. The type of something is expressed as metadata on this object.

    Tests
  • also use metadata. when you (or lein) call run-tests , it looks at the metadata of the functions in each namespace to find those that are tests.

There are many other cases, ranging from the core of a language, such as types, to peripheral objects, such as n-repl / cider, that display function arguments at the bottom of the screen while working with metadata. It’s not a designer smell to use metadata unless you use it to do ugly things, of course;)

+5
source share

All Articles