【问题标题】:More readable messages with :pre and :post?:pre 和 :post? 更易读的消息?
【发布时间】:2015-06-06 20:35:31
【问题描述】:

在 clojure 中我正在使用 :pre 像这样

user=> (defn cannot-take-empty [x] {:pre [((complement empty?) x)]} 1)
#'user/cannot-take-empty
user=> (cannot-take-empty #{})
AssertionError Assert failed: ((complement empty?) x)  user/cannot-take-empty (NO_SOURCE_FILE:186)

这很好,但它没有解释为什么传入空集合没有意义的商业原因。 (或者一个包含五个以上元素的集合,或者一个存在两个键但没有另一个键的集合,或者无论当天的规则是什么。)如果前置条件使用私有函数,这可能会让用户更加困惑。

在使用 :pre 和 :post 时,有没有办法向用户提供更有用的反馈,例如错误消息?

【问题讨论】:

  • 看看this answer 有点丑但是应该可以。
  • @soulcheck 我希望避免显式抛出异常,这似乎是java-esque。
  • 你总是可以将它包装在一个函数/宏中 (defn wrapper [c text] (if (not c) (throw (AssertionError. text)))) 但是是的,不好。

标签: clojure contracts


【解决方案1】:

显然,前置条件和后置条件是为报告条款为开发人员提供足够信息的用例而设计的,即它是不言自明的。如果您想提供更多解释,使用assert 是惯用的。

但是您可以滥用始终报告整个情况的事实,例如像这样:

{:pre [(do "It can't be empty because of..."
           (seq x))]}

它会报告类似

AssertionError Assert failed: (do "It can't be empty because of..." (seq x)) ...

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2015-08-09
    • 2020-06-24
    • 2011-04-17
    • 2021-12-17
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多