Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

宏 视频课程 问题收集 #2

Open
jiacai2050 opened this issue Dec 19, 2017 · 2 comments
Open

宏 视频课程 问题收集 #2

jiacai2050 opened this issue Dec 19, 2017 · 2 comments

Comments

@jiacai2050
Copy link
Owner

No description provided.

@shjanken
Copy link

shjanken commented Dec 19, 2017

纠结应该使用宏还是函数

;; 我有很多表在数据库里面
;; 他们有差不多的操作
;;

(defn create-fun-name [table-name op]
  (symbol (str table-name "-" op)))


(defn deftable-op [table-name]
  "将一样的操作抽象出来,比如: select all 和 delete id 等于 19 的记录"
  (let [add-fun-name (create-fun-name table-name "select-all")
        delete-fun-name (create-fun-name table-name "delete")]
    (intern *ns* add-fun-name
            (fn [] 
              (str "select * from " table-name " where 1=1")))
    (intern *ns* delete-fun-name
            (fn [] (str "delete from " table-name " where id=19")))))

(comment
  (deftable-op "foo") 
  ;; => sample.core/foo-delete

  (foo-select-all) ; 可以直接使用自动生成的函数, 下同
  ;; => "select * from foo where 1=1"

  (foo-delete)
  ;; => delete from foo where id=19

  (deftable-op "bar")
  ;; => sample.core/bar-delete

  (bar-select-all)
  ;; => select * from bar where 1=1

  (bar-delete)
  ;; => delete from bar where id=19
  )

;; 宏代码 略

@jiacai2050
Copy link
Owner Author

jiacai2050 commented Dec 23, 2017

对于你这个例子,觉得宏的优势更大一些,原因如下:

  1. 宏是在编译时运行,deftable-op 如果使用 宏定义,那么其对应表的 CRUD 操作在编译时就完成了,不会损害运行时性能
  2. 参考 Korma,如无特殊需求,建议使用成熟的第三方库

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants