7

我更喜欢 Lisp 变体中的示例(Clojure 或 Scheme 的加分项),因为这是我最熟悉的,但任何关于函数式语言中 DBC 的反馈当然对更大的社区都很有价值。

这是一个明显的方法:

(defn foo [action options]
    (when-not (#{"go-forward" "go-backward" "turn-right" "turn-left"} action)
              (throw (IllegalArgumentException.
                     "unknown action")))
    (when-not (and (:speed options) (> (:speed options) 0))
              (throw (IllegalArgumentException.
                     "invalid speed")))
    ; finally we get to the meat of the logic)

我不喜欢这个实现的是合约逻辑模糊了核心功能;该函数的真正目的在条件检查中丢失了。这与我在这个问题中提出的问题相同。在像 Java 这样的命令式语言中,我可以使用文档中嵌入的注释或元数据/属性将合同从方法实现中移出。

有没有人研究过在 Clojure 中向元数据添加合同?如何使用高阶函数?还有哪些其他选择?

4

2 回答 2

4

Clojure 已经支持前置条件和后置条件,遗憾的是没有很好的文档记录:

我应该使用函数还是宏来验证 Clojure 中的参数?

于 2009-12-09T16:00:57.103 回答
3

我可以在 Clojure 中想象这样的事情:

(defmacro defnc
  [& fntail]
  `(let [logic# (fn ~@(next fntail))]
     (defn ~(first fntail)
       [& args#]
       (let [metadata# (meta (var ~(first fntail)))]
         (doseq [condition# (:preconditions metadata#)]
           (apply condition# args#))
         (let [result# (apply logic# args#)]
           (doseq [condition# (:postconditions metadata#)]
             (apply condition# result# args#))
           result#)))))

(defmacro add-pre-condition!
  [f condition]
  `(do
     (alter-meta! (var ~f) update-in [:preconditions] conj ~condition)
     nil))

(defmacro add-post-condition!
  [f condition]
  `(do
     (alter-meta! (var ~f) update-in [:postconditions] conj ~condition)
     nil))

一个示例会话:

user=> (defnc t [a test] (a test))
\#'user/t
user=> (t println "A Test")
A Test
nil
user=> (t 5 "A Test")
java.lang.ClassCastException: java.lang.Integer (NO_SOURCE_FILE:0)
user=> (add-pre-condition! t (fn [a _] (when-not (ifn? a) (throw (Exception. "Aaargh. Not IFn!")))))
nil
user=> (t 5 "A Test")
java.lang.Exception: Aaargh. Not IFn! (NO_SOURCE_FILE:0)
user=> (t println "A Test")
A Test
nil

因此,您可以定义函数,然后根据需要定义前置条件和后置条件,而不会弄乱函数逻辑本身。

如果出现问题,条件函数应该抛出异常。

于 2009-12-08T12:54:12.650 回答