Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "if" and "when" in Clojure?

When is one better than the other? Is one faster than the other or does the only difference is the return of false or nil?

like image 760
Alonzorz Avatar asked Sep 20 '14 11:09

Alonzorz


2 Answers

Use if when you have exactly one truthy and one falsy case and you don't need an implicit do block. In contrast, when should be used when you only have to handle the truthy case and the implicit do. There is no difference in speed, it's a matter of using the most idiomatic style.

 (if (my-predicate? my-data)
     (do-something my-data)
     (do-something-else my-data))

 (when (my-predicate? my-data)
     (do-something my-data)
     (do-something-additionally my-data))

In the if case, only do-something will be run if my-predicate? returns a truthy result, whereas in the when case, both do-something and do-something-additionally are executed.

like image 191
schaueho Avatar answered Oct 27 '22 17:10

schaueho


Use if when you have two different expressions: for true clause and for false clause.

when and when-not are useful in two cases:

  • when you want to perform one or several (implicit do helps here) non-pure operations conditionally;
  • when you want to evaluate something when some predicate evaluates to true (or false in case of when-not), and return nil in opposite case.

only difference is the return of false or nil

There is no major difference between false and nil, as the both evaluate to false in logical context.

like image 9
Mark Karpov Avatar answered Oct 27 '22 18:10

Mark Karpov