在Clojure中检查函数参数是否为nil而不抛出断言的一种不那么麻烦的模式



这里有人问过这个问题,但答案都是不可接受的。

我正在尝试将一些防御性编程技术应用于clojure,但我发现有些事情很麻烦。

类似检查功能参数:

(defn my-tolower [s]
(if (nil? s) nil
(.toLowerCase s)
))

有更干净的方法吗?

我知道:pre,但这引发了一个异常。

您似乎只是想要some->,不是吗?

(defn my-tolower [s]
(some-> s .toLowerCase))
(my-tolower "HELLO") => "hello"
(my-tolower     nil) => nil

或者只内联它而不使用包装器函数:

(some-> "HELLO" .toLowerCase)   => "hello"
(some->  nil    .toLowerCase)   => nil

由于nil是假的,您可以使用when:

(when s (.toLowerCase s))

如果你想要测试,你可以使用some?而不是nil?:

(if (some? s) (.toLowerCase s))

还有其他解决方案:

fnil,可能是我会做的

clojure.core/fnil
([f x] [f x y] [f x y z])
Takes a function f, and returns a function that calls f, replacing
a nil first argument to f with the supplied value x. Higher arity
versions can replace arguments in the second and third
positions (y, z). Note that the function f can take any number of
arguments, not just the one(s) being nil-patched.

为nil接受fn提供默认值。/

(let [f (fnil str/lower-case "")]
(f nil))
""

或捕捉NPE

(let [f str/lower-case] 
(try (f nil) 
(catch NullPointerException ne nil)))
""

或仅str

(.toLowerCase (str nil))
""

CCD_ 8和CCD_

最新更新