There's something I don't understand very well when I read Clojure code (say from various projects on GitHub): in the :require
expression, are you supposed to use :as
when you're only using functions that you're referring to using :refer
? Also I'm not too sure if there's any difference between Clojure and ClojureScript from that standpoint, nor if there's any convention.
For example (I'm using the cats library for the examples but that's just an example) if I do this:
(ns example.core
(:require
[cats.core]
[cats.monad.maybe :as maybe]))
from, say, the REPL I can do this:
REPL> (cats.core/mappend (maybe/just 1))
But it's not very convenient, so I may do this instead:
(ns example.core
(:require
[cats.core :as m]
[cats.monad.maybe :as maybe]))
REPL> (m/mappend (maybe/just 1))
Now in case I use mappend
(and a few others) all the time, I could do:
(ns example.core
(:require
[cats.core :refer [mappend]]
[cats.monad.maybe :as maybe]))
REPL> (mappend (maybe/just 1))
So my question is: is there any use in using both :as
and :refer
, like in the following example?
(ns example.core
(:require
[cats.core :as m :refer [mappend]] ; does this make any sense?
[cats.monad.maybe :as maybe]))
I understand that I may be using, say, mappend
all the time and may want to refer to it directly as mappend
but bind
not that often as to using :refer
but yet often enough so that writing cats.core/bind
is not convenient, so I'd use m/bind
?
So is there any rule? Like if you're using :as
you should not use :refer
, or the other way round? Or that you should always use both?
What about ClojureScript, is it working in exactly the same way?
You're right on the use case; things that you use quite often, you may want to :refer
to directly, otherwise, just use the :as
alias to access it. There's no problem with doing both.
I personally tend to prefer :as
unless it's very clear what namespace the :refer
ed function came from (e.g. I would recognize >!!
without a prefix, but find m/bind
more readable).
The most widely used style guide afaik suggests that using them in conjunction is fine, but prefer :as
to :refer
in most cases: https://github.com/bbatsov/clojure-style-guide#comprehensive-ns-declaration
Clojurescript should be exactly the same for :refer
and :as
in ns
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With