Should I use a function or a macro to validate arguments in Clojure?

后端 未结 3 2046
慢半拍i
慢半拍i 2020-12-29 10:40

I have a group of numeric functions in Clojure that I want to validate the arguments for. There are numerous types of arguments expected by the functions, such as positive i

3条回答
  •  -上瘾入骨i
    2020-12-29 10:59

    Just a few thoughts.

    I have a feeling it depends on the complexity and number of validations, and the nature of the functions.

    If you are doing very complex validations, you should break your validators out of your functions. The reasoning is that you can use simpler ones to build up more complex ones.

    For example, you write:

    1. a validator to make sure a list is not empty,
    2. a validator to make sure a value is greater than zero,
    3. use 1 and 2 to make sure a value is a non empty list of values greater than zero.

    If you're just doing a huge amount of simple validations, and your issue is verbosity, (e.g. you have 50 functions that all require non-zero integers), then a macro probably makes more sense.

    Another thing to consider is that function evaluation is Clojure is eager. You could get a performance boost in some cases by not evaluating some parameters if you know the function will fail, or if some parameters are not needed based on values of other parameters. E.g. the every? predicate doesn't need to evaluate every value in a collection.

    Finally, to address "others you haven't thought of". Clojure supports a generic dispatching pbased on a dispatch functon. That function could dispatch to appropriate code, or error messages based on any number of factors.

提交回复
热议问题