【问题标题】:Can one make a Clojure spec private?可以将 Clojure 规范设为私有吗?
【发布时间】:2019-09-15 12:04:58
【问题描述】:

我有一个“vertex”(平面中的 2D 点,用包含两个双精度值的地图表示)和一个“rectangle”(一个平面中轴对齐的矩形区域,由两个“vertex”值的映射表示),定义如下:

; vertex coordinates are doubles (need to make sure "=" doesn't try to
; compare floats in one vertex and doubles in another one, which fails)

(s/def ::vtx-x double?)
(s/def ::vtx-y double?)

; vertex is a map representing a 2D point

(s/def ::vertex (s/keys :req [::vtx-x ::vtx-y]))

; rectangle corners "low" (low x,y) and "high" (high x,y) are vertexes

(s/def ::rec-lo ::vertex)
(s/def ::rec-hi ::vertex)

; rectangle has internal sorting constraint, specified via a predicate

(s/def ::rectangle-internally-sorted
   (fn [rect]
      (let [lo-vtx (::rec-lo rect)
            hi-vtx (::rec-hi rect)
            lo-x   (::vtx-x lo-vtx)
            lo-y   (::vtx-y lo-vtx)
            hi-x   (::vtx-x hi-vtx)
            hi-y   (::vtx-y hi-vtx)]
          (< lo-x hi-x) (< lo-y hi-y))))

; rectangle is a map of two vertexes 
; representing an axis-aligned rectangular area

(s/def ::rectangle
   (s/and
      (s/keys :req [::rec-lo ::rec-hi])
      ::rectangle-internally-sorted))

客户端代码应该只能使用规范 ::vertex 和 ::rectangle。

我可以隐藏(私有化)支持规范吗?

【问题讨论】:

    标签: clojure clojure.spec


    【解决方案1】:

    你不能也不应该。隐藏底层规范只会妨碍用户使用您的规范,因为他们无法理解规范或生成故障,或s/form 返回的表单。从这个意义上说,组件规范不是实现细节,它们不可避免地会以某种方式呈现给消费者。

    不过,规范是命名空间的。您当然可以将内部组件移动到不同的名称空间,您可以为消费者声明越界。我会问从中可以得到什么;在 Clojure 中,信息隐藏从来没有被强调过,尤其是规范(一种数据描述语言),在我看来,公共/私人的区别有点不合适。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2020-08-07
    • 2020-07-08
    • 2017-10-08
    • 2019-05-06
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多