On 10 February 2011 21:33, Fogus <mefo...@gmail.com> wrote:
> Additionally, I've always hoped for separate
> PreConditionAssertionError and PostConditionAssertionError types, but
> keep forgetting to discuss it.

A while ago Stuart Sierra wrote about using typed assertions in unit
testing. One of his points was to give test functions the ability to
explain why they fail, instead of simply returning false. Rich raised
some interesting arguments contra more exception types, and pro more
value-oriented exceptions:

http://stuartsierra.com/2010/07/19/typed-assertions#comment-43140

>> (defn f [x] {:pre [^{:msg "..."} (some-fancy-validation x)]} ..)
>
> That idea (or some variation) is actually kinda nice.

Personally, I find the suggested syntax a bit verbose. Consider this:

(defn mangle-fullname [firstname lastname]
  {:pre [^{:msg "firstname must be a string of 10 to 50 characters"}
(valid-firstname? firstname),
       ^{:msg "lastname must be a string of 20 to 70 characters"}
(valid-lastname? lastname)]}
  (body-that-may-be-shorter-than-above-conditions))

How about integrating these messages into the validator functions?
They are allowed to raise exceptions themselves:

(defn valid-firstname? [firstname]
  (if-not (string? firstname)
    (throw (AssertionError. "firstname must be a string")))
  (if-not (<= 10 (count firstname) 50)
    (throw (AssertionError. "firstname must be between 10 to 50
characters long"))
  true))

Note the "true" return value, otherwise the precondition will raise an
assertion error itself. Of course, this is still overly verbose, but
at least the verbosity is taken away from mangle-fullname's
definition.

Bummer that 'assert doesn't take an optional failure message, by the
way. 'assert-args does:

(defn mangle-fullname [firstname lastname]
  (assert-args mangle-fullname
    (string?) firstname "a string for firstname"
    (<= 10 (count firstname) 50) "firstname to be between 10 to 50
characters long"
    ...))

user=> (mangle-fullname "Adam" "West")
IllegalArgumentException: mangle-fullname requires firstname to be
between 10 to 50 characters long

This doesn't allow to factor out the error message into a separate
validator function, though.

Daniel

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to