Everyday branching tools beyond if: when, if-let/when-let, cond, and case (plus the truthiness rules that matter).
In Clojure, most “control structures” are macros built on top of a small set of special forms. The goal is not to memorize them all, but to recognize the ones you’ll read constantly.
One truthiness rule matters everywhere:
false and nil are falsey0, "", [], {})when / when-not (Side-Effect-Friendly Branching)Use when when you only need the “then” branch:
1(when (pos? n)
2 (println "positive")
3 (inc n))
It evaluates to the last expression in the body, or nil if the condition is false.
when-not is the negated version.
if-let / when-let (Bind and Check in One Step)These are idiomatic for nil-checking while naming the value:
1(if-let [email (:email user)]
2 (send-email! email)
3 (println "User has no email"))
nil for when-let)cond (Multi-Branch)cond is the “ladder” form when you have multiple tests:
1(cond
2 (nil? x) :missing
3 (neg? x) :negative
4 :else :ok)
case (Fast Dispatch on Constants)Use case when you’re matching against constants (similar to a Java switch):
1(case status
2 :ok 200
3 :fail 500
4 400) ; default