Suppose I have a python function like this:
def required(value):
if value is None:
throw Exception
if isintance(value, str) and not value:
throw Exception
return value
Basically I want to check if the value is null or not. If the value is a String, also check if it's empty or not.
What is the clojure way of doing something like this?
The Clojure way of doing something like this is not to throw exceptions or so. The idiomatic way would be something that returns nil and nothing else.
So my advise: Do this without exceptions.
Your function will then look like this:
(defn required [value]
(when (string? value)
value))
It checks for the type of value and returns nil if it is not a String. Otherwise return your value.
Or if you want an error message in your terminal:
(defn required [value]
(if (string? value)
value
(println "Value must be a String.")))
Note that println prints the String and then returns again nil.
Preconditions would do the trick nicely in this instance. Otherwise use Clojure's control flow special forms/macros, e.g. if, cond with 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With