clojure - clojure/clojurescript 中单个 var 命名空间的命名约定是什么?

标签 clojure namespaces naming-conventions clojurescript

我经常发现自己在 clojurescript 中定义的命名空间只包含一个通过 def 或 defn 创建的 var,我将在该命名空间之外使用它。

这在使用 时尤为常见。 ,我在单独的文件/命名空间中定义我的组件,并且我只在命名空间之外使用这些单个组件。

(ns project.components.component-name)
(defn component-name ...)

所以我以这种方式导入它们,我发现它非常重复且不清楚,因为命名空间和组件都使用了一个名称:
project.components.component-name :as [component-name]

component-name/component-name

或劣等 :refer (因为 var 来自另一个命名空间不太明显)
project.components.component-name :refer [component-name]

component-name

我知道在 ECMAScript 中有一个有用的模式:
export default function () { ... };

那么Clojure中有这样的东西吗?或者也许有一些既定的约定?

下面是我最近开始使用的约定,我对此非常不确定。
(ns project.components.component-name)
(defn _ ...)

project.components.component-name :as [component-name]

然后将其用作
component-name/_

最佳答案

下划线通常用于表示您在 Clojure 中不关心的值,因此我强烈建议您避免使用 _作为函数名。例如,您经常会在野外看到这样的代码:

;; Maybe when destructuring a let. Kinda contrived example.
(let [[a _ _ d] (list 1 2 3 4)]
   (+ a d 10))

;; Quite often in a protocol implementation where we don't care about 'this'.
(defrecord Foo []
  SomeProtocol
  (thing [_ x]
    (inc x)))

在命名空间中使用单个 var 并没有错,尽管我可能只会在有合理的功能块时才引入命名空间。您可以尝试使用像 my-app.components 这样的命名空间在那里你保留所有的小东西,直到它们大到足以保证一个专用空间。类似的东西:
(ns my-app.components
  ;; The profile stuff is really big lets say.
  (:require [my-app.components.profile :as profile]))

(defn- items->ul
  [items]
  [:ul (map #(vector :li (:text %)) items)])

(defn- render-nav
  [state]
  [:nav (-> state deref :nav-items items->ul)])

(defn- render-footer
  [state]
  [:footer (-> state deref :footer-items items->ul)])

(defn render-layout
  [state]
  [:html
   [:head [:title (:title @state)]]
   [:body
    [:main
     (render-nav state)
     (profile/render-profile (-> state deref :current-user))
     (render-footer state)]]])

关于clojure - clojure/clojurescript 中单个 var 命名空间的命名约定是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42701553/

相关文章:

clojure - 我想在 clojure 的沙盒命名空间中运行加载文件

java - Java 中 "public static final"常量的 Clojure 等价物是什么

c++ - 'drv' 没有命名类型

javascript - 跨多个文件的 Typescript 内部模块与 js 缩小

c - C中构造函数和析构函数的命名约定

当一个宏调用另一个宏时的 Clojure 宏和默认参数

java - 用于基于 map 调用 Java setter 的 Clojure 宏?

C++ 命名空间问题

naming-conventions - 缩写 impl 用于很多库中;这是什么意思?

java - keystore (java)是否有命名约定