Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some Clojure library which has a function acts as Java's StringUtils.defaultIfBlank(str, default)?

Tags:

string

clojure

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.

like image 668
philipjkim Avatar asked Mar 13 '23 17:03

philipjkim


1 Answers

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.

like image 185
Arthur Ulfeldt Avatar answered Apr 29 '23 08:04

Arthur Ulfeldt