gpt4 book ai didi

clojure - 为什么你应该选择 :require :refer :all over :use in clojure

转载 作者:行者123 更新时间:2023-12-03 00:06:49 24 4
gpt4 key购买 nike

在他的Clojure Style Guide中作者写了以下内容,

Prefer using :require :refer :all over :use in ns macro

他没有给出任何解释为什么这是一个好主意。有没有避免在 ns 宏中使用 :use 的充分理由?

最佳答案

我建议您看一下original discussion ,这导致了这个规则。核心原理可参见here 。我将在此处开始讨论:

There's been discussion previously about the complexity of the ns macro. In particular the fact that :use causes all vars to be referred by default is widely seen as unfortunate, and the distinction between use and require is a source of conceptual overhead for people new to the language. We can't change the fact that :use refers everything by default without breaking lots of existing code. But it would be possible to enhance :require to support referring specified vars, leaving us free to deprecate or otherwise discourage the use of :use.

Rather than this form:

(ns mork.test
(:use [mork.stats :only [summarize-group]]
[mork.utils :only [strip resolve-fn]]
[clojure.test])
(:require [mork.view :as view]
[clojure.java.io :as io]
[cheshire.core :as json])
(:import (java.io PushbackReader))

We could use this:

(ns mork.test
(:require [mork.stats :refer [summarize-group]]
[mork.utils :refer [strip resolve-fn]]
[clojure.test :refer :all]
[mork.view :as view]
[clojure.java.io :as io]
[cheshire.core :as json])
(:import (java.io PushbackReader))

It has been agreed upon in previous threads that keeping :import as a distinct concept from :require is desirable, and I agree that we shouldn't conflate between Clojure vars and Java classes.

There are rare cases when referring all the vars in a namespace is acceptable, (in particular when writing test namespaces it seems reasonable to bring in all of clojure.test and the namespace under test) so we should probably support :refer :all for such a case, as long as it's not the default.

关于clojure - 为什么你应该选择 :require :refer :all over :use in clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22982303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com