Anti-If: The missing patterns (2016)
Another pattern I've found helpful is to have branches "exit early"; if you have code like:<p><pre><code>    if !cache.contains(key) {
      v = db.query("..")
      expiry = calcexpiry(v)
      cache.put(k, v, expiry)
      return v;
    } else {
      return cache.get(k)
    }
</code></pre>
by the time you get to the "else", your mental stack is filled up with the cache loading logic - you have to work to recall what this else branch is triggered by.<p>instead, make the branch be the least complex option and exit early, and skip the else. That way, it can be read as "if this condition, do this tiny logic and exit", and that branch can then be mentally pruned.<p><pre><code>    if cache.contains(key) {
      return cache.get(key)
    }
    
    v = db.query("..")
    expiry = calcexpiry(v)
    cache.put(k, v, expiry)
    return v;</code></pre>