DEV Community

Discussion on: 1 small tip to improve your code readability

kallmanation profile image
Nathan Kallman

I love guard clauses like these! Thanks for the article

They're especially helpful when multiple conditions should be checked (aka a "preflight checklist")


function doSomething(a,b) {
  if(a && a.type == "correct" && b && b.type == "correct" && a.timestamp >= b.timestamp)
    /* ... */

to the guard version:

function doSomething(a, b) {
  if (!a) return;
  if (a.type != "correct") return;
  if (!b) return;
  if (b.type != "correct") return;
  if (a.timestamp < b.timestamp) return;
  /* ... */

The guard version:

  1. has less indention
  2. has more separation of logic
  3. minimizes diffs in line based version control (aka git) when changing conditions

(and in a language like Ruby, something I particularly like is if(!a) return guard clauses can be rewritten as return unless a)

king11 profile image
Lakshya Singh

Optional Channing can use reduce the lines i believe 🤔