if-else branching in clojure

This is the subtle difference between imperative and functional approach. With imperative, you can place return in any place of the function, while with functional the best way is to have clear and explicit exeecution paths. Some people (me including) prefer the latter approach in imperative programming as well, recognizing it as more obvious and manageable and less error-prone.

To make this function explicit:

Thing myfunc() {
  if(cond1) {
    if(cond2)
      return something;
  }

  return somethingelse;
}

You can refactor it to:

Thing myfunc() {
  if(cond1 && cond2) {
      return something;
  } else {
    return somethingelse;
  }
}

In Clojure, its equivalent is:

(defn myfunc []
  (if (and cond1 cond2) 
      something
      somethingelse))

If you need an “else”, your Java version could become:

Thing myfunc() {
  if(cond1) {
    if(cond2) {
      return something;
    } else {
      return newelse;
    }
  } else {
    return somethingelse;
  }
}

… and its Clojure equivalent:

(defn myfunc []
  (if cond1
      (if cond2 something newelse)
      somethingelse))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)