2017-03-09 121 views
1

我經常發現自己定義了clojurescript中的名稱空間,它只包含通過def或defn創建的一個var,我將在該名稱空間之外使用它。clojure/clojurescript中的單個var命名空間的命名約定是什麼?

這在使用時尤爲常見,我在其中定義我的組件在單獨的文件/名稱空間中,而且我只在名稱空間外使用這些單個組件。

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

於是我進口他們這樣,我覺得它非常重複性和不明確的,因爲是同時用於命名空間和組件一個名字:

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

component-name/component-name 

或劣:參考(因爲它是那麼明顯該變種來自另一個命名空間的)

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/_ 

回答

1

下劃線通常用於你不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))) 

沒有錯,通過具有在命名空間中的單個變種是,雖然我可能會只介紹一個命名空間時,有功能性的合理份額。你可以嘗試一個像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)]]]) 
1

我不知道每個命名空間的一個組件是最好的方法。這將導致 在大量的命名空間和相當多的重複。然而,這是 clojure和每個人都有不同的風格。我的方法是使用命名空間 來分解功能。除了最簡單的 組件之外,我發現組件不會使用其他組件也很少見。我傾向於將特定功能中使用的所有組件和用於大多數其他組件的各種低級組件組合在一起,並具有/ utility /或/ base /名稱空間。例如,我可能 有類似

project --| 
      src --| 
       my-app --| 
         core.cljs 
         interface --| 
            base.cljs 
            navbar.cljs 
            sidebar.cljs 
            tabber.cljs 

在每一個這些命名空間中,可能有多個組件。其中一些可能被定義爲對該名稱空間是私有的,而其他的是 被core.cljs引用的條目組件。我發現命名空間需要部分不要太大 大或重複,我不需要在不同的文件中跳轉多達 YMMV。