user2219372
user2219372

Reputation: 2455

what's the elegant way to write this code in clojure?

I use Clojure and korma libs.

defn db-search-users
  [& {:keys [nick_name max_age min_age page page_size lmt oft]
      :or {lmt 10  page_size 10 oft 0 }
      :as conditons}]
  (let [users-sql  (-> (select* users)
                       (fields :user_name :id :nick_name)
                       (limit (if (nil? page) lmt page_size))
                       (offset (if (nil? page) oft (* page page_size))))]
    (do
       (exec (-> users-sql
                need_do_something_here
             )
       )

  )

now I need to add some search conditions to users-sql at "need_do_something_here", I can describe it in imperative style:

if ( nick_name != nil)
    users-sql = (where users-sql (like :nick_name nick_name)

if (max_age != nil)
    users-sql = (where users-sql (> :birthday blabla....))

if (min_age != nil)
    users-sql = (where users-sql (< :birthday blabla....))

how to do this in an elegant way in a functional style?

another question is:

I find the following code ugly:

(if (nil? page) lmt page)

Is there some functions in Clojure like (get_default_value_3_if_a_is_null a 3) ?

Upvotes: 1

Views: 163

Answers (1)

user2219372
user2219372

Reputation: 2455

get my answer from A.Webb,now my code is :

(defn db-search-users
  [& {:keys [nick_name max_age min_age page page_size lmt oft]
      :or   {lmt 10 page_size 10 oft 0}
      :as   conditons}]
  (let [users-sql (-> (select* users)
                      (fields :user_name :id :nick_name :password)
                      (limit (if (nil? page) lmt page_size))
                      (offset (if (nil? page) oft (* page page_size))))
        normal_conditions (select-keys conditons [:user_name :gender :phone])]
    (exec (cond-> users-sql
                  (not-empty normal_conditions) (where normal_conditions)
                  (not-nil? nick_name) (where (like :nick_name (str "%" nick_name "%")))
                  (not-nil? max_age) (where (> :birthday (c/to-sql-date (-> max_age t/years t/ago))))
                  (not-nil? min_age) (where (< :birthday (c/to-sql-date (-> min_age t/years t/ago))))
                  )
          )

    )
  )

cond-> is perfect way to deal with my question.

the second question :how to beautify code like

(if (nil? page_size) lmt page_size) 

now get think map data structure can be used for this case.

Upvotes: 1

Related Questions