简体   繁体   中英

What's idiomatic clojure for :use

I've seen several different ways for :use in clojure--what's the idiomatic/preferred method?

#1

(ns namespace.core
  (:use [[something.core]
         [another.core]]))

or #2 EDIT: Use this with conjunction with :only .

(ns namespace.core
  (:use [something.core]
        [another.core]))

or #3

(ns namespace.core
  (:use [something.core
         another.core]))

or #4

(ns namespace.core
  (:use (something.core
         another.core)))

or #5 EDIT: This is idiomatic, but one should be using :use as in #2

(ns namespace.core
  (:use something.core
        another.core))

Choice #5 is idiomatic, unless you are passing additional options such as :only, :exclude, etc. Colin's blog post covers the options in great detail.

The API for dealing with namespaces is unnecessarily difficult to learn. However, it is certainly capable enough for a wide variety of uses, so the pressure for a rewrite has yet to reach the boiling point for anyone.

Actually none of them are idiomatic. You should always have an :only clause in your :uses. Your best bet is adding :only to #2. If you don't want to enumerate all the vars you're taking from another namespace, consider (:require [foo.bar :as bar]).

One point of note that we should mention is that the (:use (clojure set xml)) statement is considered a promiscuous operation and therefore discouraged. [...] When organizing your code along namespaces, it's good practice to export and import only those elements needed.

-from the Joy of Clojure, page 183.

The one exception is that a test namespace should bare-use the namespace it tests.

The cases 1, 3 and 4 are not valid and throw some Exception. I haven't seen 2 - only in combination with :only or the like.

(ns namespace.core
  (:use
    [something.core :only (x)]
    another.core))

I usually use 5.

In Clojure 1.4+ I wouldn't use use at all. require can do all that use can do now, so forget about use . One less thing to worry about.

If you want use -like behaviour (still bad form, imo) you can do:

(ns namespace.core
  (:require
    [something.core :refer :all]
    [another.core :refer :all]))

If you want :use .. :only behaviour, use:

(ns namespace.core
  (:require
    [something.core :refer [foo bar]]
    [another.core :refer [quux]]))

More detail: In Clojure 1.4 what is the use of refer within require?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM