符合命名空间的记录字段访问器 [英] Namespace qualified record field accessors

查看:75
本文介绍了符合命名空间的记录字段访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次犯同样的愚蠢错误:

I've made the same dumb mistake many many times:

(defrecord Record [field-name])

(let [field (:feld-name (->Record 1))] ; Whoops!
  (+ 1 field))

由于我拼错了字段名关键字,这将导致NPE.

Since I misspelled the field name keyword, this will cause a NPE.

对此的明显"解决方案是让defrecord发出命名空间的关键字,此后,尤其是在其他文件中工作时,IDE能够在我键入时立即显示可用的关键字. ::n/.

The "obvious" solution to this would be to have defrecord emit namespaced keywords instead, since then, especially when working in a different file, the IDE will be able to immediately show what keywords are available as soon as I type ::n/.

我可能可以凭借一些创造力来创建一个包装defrecord的宏,该宏为我创建了关键字,但这似乎有点过头了.

I could probably with some creativity create a macro that wraps defrecord that creates the keywords for me, but this seems like overkill.

是否有一种方法可以使defrecord发出命名空间的字段访问器,或者还有其他避免该问题的好方法吗?

Is there a way to have defrecord emit namespaced field accessors, or is there any other good way to avoid this problem?

推荐答案

因为defrecords可以编译为java类,而java类上的字段没有名称空间的概念,所以我认为没有很好的方法来进行defrecord发出命名空间的关键字.

Because defrecords compile to java classes and fields on a java class don't have a concept of namespaces, I don't think there's a good way to have defrecord emit namespaced keywords.

如果代码对性能不敏感并且不需要实现任何协议等类似方法,则可以选择仅使用地图.

One alternative, if the code is not performance sensitive and doesn't need to implement any protocols and similar, is to just use maps.

另一种方法是像Alan Thompson的解决方案一样,进行安全获取功能. prismatic/plumbing util库也有一个实现.

Another is, like Alan Thompson's solution, to make a safe-get funtion. The prismatic/plumbing util library also has an implementation of this.

(defn safe-get [m k]
  (let [ret (get m k ::not-found)]
    (if (= ::not-found ret)
      (throw (ex-info "Key not found: " {:map m, :key k}))
      ret)))

(defrecord x [foo])

(safe-get (->x 1) :foo) ;=> 1

(safe-get (->x 1) :fo) ;=>

;; 1. Unhandled clojure.lang.ExceptionInfo
;;  Key not found:
;;  {:map {:foo 1}, :key :fo}

这篇关于符合命名空间的记录字段访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆