I need a function which takes two parameters input
string and default
string, then return input
if not blank, or default
.
(defn default-if-blank [input default]
(if (clojure.string/blank? input)
default
input))
I can implement the function, but I think there would be lots of good utility libraries in Clojure world, such as Apache commons or Guava in Java world.
Is it common that implementing such functions by myself, rather than using some libraries? I'm new to Clojure, so this can be stupid question but any advices will help me. Thanks.
What you have there is very normal and would be perfectly fine in high quality Clojure code. It's completely ok to write this way, because Clojure is a terse language this does not add much intellectual overhead.
In some cases you would not need it, for instance if you are pulling values from any of the collections, get
takes an optional default parameter:
user> (get {1 "one" 2 "two"}
42
"infinity")
"infinity"
and optional parameters when destructing things like maps:
user> (let [{a :a b :b c :c :or {a :default-a
b :default-b}}
{:a 42 :c 99}]
(println "a is" a)
(println "b is" b)
(println "c is" c))
a is 42
b is :default-b
c is 99
make it less common to need these situations, though there are plenty of (if (test foo) foo :default)
cases in the codebase I work with on a daily basis. It has not been common and consistent for us in a way that would lend itself to being consolidated as you have done.
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