假设我具有这样的python函数:
def required(value):
if value is None:
throw Exception
if isintance(value, str) and not value:
throw Exception
return value
基本上,我想检查值是否为null。如果值是字符串,也请检查其是否为空。
这样做的事情是什么?
这样做类似的事情是而不是投掷异常。惯用方式将是返回 nil
而别无其他的东西。
所以我的建议:毫无例外地执行此操作。
您的功能将看起来像这样:
(defn required [value]
(when (string? value)
value))
它检查值的类型,如果不是字符串,则返回nil
。否则返回您的价值。
或如果您在终端中想要错误消息:
(defn required [value]
(if (string? value)
value
(println "Value must be a String.")))
请注意,println
打印字符串,然后再次返回nil
。
前提条件在这种情况下可以很好地完成。否则,请使用Clojure的控制流特殊表单/宏,例如 if
, cond
带throw
。
user=> (defn required
[value]
{:pre [(string? value) (not-empty value)]}
value)
#'user/required
user=> (required nil)
AssertionError Assert failed: (string? value) user/required ...
user=> (required "")
AssertionError Assert failed: (not-empty value) ...
user=> (required "foo")
"foo"
以前的两个答案在断言上都是有些错误的。我是布迪要求的是:
(defn required [value]
(if (or (nil? value)
(and (string? value) (clojure.string/blank? value)))
(throw (Exception.))
value))
a。韦伯是正确的,因为前提是一种很好的,惯用的方式来代表您在这里尝试做的事情。
对于它的价值,这是您如何使用明确的异常和 cond
ition语句来做同样的事情:
(defn required [value]
(cond
(not (string? value))
(throw (IllegalArgumentException. "Value must be a string."))
(empty? value)
(throw (IllegalArgumentException. "String cannot be empty."))
:else
value))
或更愚蠢的是,首先使用when
处理错误,然后在末尾返回值:
(defn required [value]
(when (not (string? value))
(throw (IllegalArgumentException. "Value must be a string.")))
(when (empty? value)
(throw (IllegalArgumentException. "String cannot be empty.")))
value)